可能的重复:
循环Json对象 https://stackoverflow.com/questions/684672/loop-through-json-object
我有一个 PHP 函数,data.php
,它从外部服务器 URL 获取 JSON 数据,如下所示:
<?php
$url = "https://dev.externalserver.net/directory";
$content = file_get_contents($url);
echo json_encode($content);
?>
检索到的 JSON 数组如下所示:
[
{ "name": "Not configured",
"mac_address": "1111c11c1111",
"online": "false",
"rate": "Not configured" },
{ "name": "Not configured",
"mac_address": "0000c00c0000",
"online": "false",
"rate": "Not configured" }
]
我现在尝试编写对该 PHP 函数的 AJAX 调用,迭代 JSON 数组,并以非 JSON 格式在浏览器中显示它。我的 AJAX 代码如下所示:
$.ajax({ url: 'data.php',
type: 'POST',
dataType: 'json',
success: function(output) {
$.each(output, function() {
$.each(this, function(key, value){
alert(key + " --> " + value);
});
});
}
});
我的问题是代码当前显示警报框,其中显示数组中的各个字符,如下所示:0 --> [
, 0 -->
, 0 --> {
...等等等等
我使用 json_encode(); 传递数据的方式有问题吗?和 dataType: 'json' 或者问题是否通过我迭代数组的方式解决?
Thanks.