Parse PHP array of objects with jQuery Ajax

前端 未结 3 1220
悲&欢浪女
悲&欢浪女 2021-01-15 16:43

I\'m trying to get an array of objects with data from my database into jquery to render on a website.

ex: example.php



        
相关标签:
3条回答
  • 2021-01-15 17:23
    function testFunction() {
    
    $data = array();
    $mydata = new stdClass;
    $mydata->example = 'test';
    $data[] = (array) $mydata;
    return json_encode($data);
    }
    
    echo testFunction();
    

    The response is:

    [{"example":"test"}]
    

    The key here is (array) $mydata which converts the stdclass to an array before putting it in $data

    0 讨论(0)
  • 2021-01-15 17:26

    You need to JSON.parse(response); the response. You should be able to access it like you need then..

    var parsed_reply = JSON.parse(response);
    

    EDIT After actually looking at the code:

    PHP

    <?php
    
    $data['example'] = "test";
    
    echo json_encode($data);
    
    ?>
    

    JAVASCRIPT

    <script>
    $.ajax({
                    type: 'POST',
                    url: 'example.php',
                    data: {map: map},   
                    cache: false,
                    dataType: 'json',                 
                    success: function(response) {
                      console.log(response['example']);
                    }
    });
    
    </script>
    

    OUTPUT: "test"

    0 讨论(0)
  • 2021-01-15 17:38

    You need call testFunction() in example.php

    <?php
       function testFunction() {
    
        $data = array()
        $mydata = new stdClass;
        $data[] = $mydata->example = 'test';
    
        return json_encode($data);
      }
         echo testFunction();
    ?>
    
    0 讨论(0)
提交回复
热议问题