使用jQuery Ajax解析PHP对象数组
我正在尝试将数据库中的数据添加到jquery中以在网站上呈现。
例如:example.php
example = 'test'; $data[] = $mydata return json_encode($data); } echo testFunction(); ?>
ex index.html
$.ajax({ type: 'POST', url: 'example.php', data: {map: map}, cache: false, dataType: 'json', success: function(response) { console.log(response[0].example); } });
输出:
的console.log(响应);
[“test”,$ family:function,$ constructor:function,each:function,clone:function,clean:function …]
的console.log(响应[0]。实施例);
未定义
基本上,我收到的回复很好,当我记录它时它给了我一个有意义的结构。 但是我似乎无法找到访问数组内部对象的正确方法,上面的例子只返回undefined。 这请问的正确语法是什么?
你需要JSON.parse(response);
响应。 你应该能够像你需要的那样访问它..
var parsed_reply = JSON.parse(response);
编辑实际查看代码后:
PHP
JAVASCRIPT
输出:“测试”
你需要在example.php中调用testFunction()
example = 'test'; return json_encode($data); } echo testFunction(); ?>
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
之前将其转换为数组