Parse PHP array of objects with jQuery Ajax

2020-03-29 08:04发布

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

ex: example.php

<?php
function testFunction() {

$data = array()
$mydata = new stdClass;
$mydata->example = 'test';
$data[] = $mydata
return json_encode($data);
}

echo testFunction();
?>

ex index.html

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

</script>

Output:

console.log(response);

["test", $family: function, $constructor: function, each: function, clone: function, clean: function…]

console.log(response[0].example);

undefined

So essentially, I receive the response fine, when I log it it gives me a structure that makes sense. however I can't seem to find the correct way of accessing my objects inside the array, the example I have above only returns undefined. What is the correct syntax for this please?

3条回答
【Aperson】
2楼-- · 2020-03-29 08:16

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"

查看更多
家丑人穷心不美
3楼-- · 2020-03-29 08:18

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();
?>
查看更多
ら.Afraid
4楼-- · 2020-03-29 08:25
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

查看更多
登录 后发表回答