2

我正在尝试将包含数据的对象数组从我的数据库中获取到 jquery 中以在网站上呈现。

例如: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>

输出:

控制台日志(响应);

["test", $family: 函数, $constructor: 函数, each: 函数, 克隆: 函数, clean: 函数...]

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

不明确的

所以本质上,我收到了很好的响应,当我记录它时,它给了我一个有意义的结构。但是我似乎找不到在数组中访问我的对象的正确方法,我上面的示例只返回未定义。请问这个的正确语法是什么?

4

3 回答 3

4

你需要JSON.parse(response);回应。你应该能够像你需要的那样访问它..

var parsed_reply = JSON.parse(response);

编辑在实际查看代码后:

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>

输出:“测试”

于 2013-11-11T17:53:25.517 回答
1
function testFunction() {

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

echo testFunction();

回应是:

[{"example":"test"}]

这里的关键是在放入之前将(array) $mydata其转换stdclass为数组$data

于 2013-11-12T11:58:01.157 回答
1

您需要testFunction()在 example.php 中调用

<?php
   function testFunction() {

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

    return json_encode($data);
  }
     echo testFunction();
?>
于 2013-11-11T13:48:45.690 回答