我如何遍历使用jQuery / AJAX调用从PHP JSON数组?

问题描述:

可能重复:
  遍历JSON对象

我有一个PHP函数, data.php ,从像这样一个外部服务器的URL获取JSON数据:

I have a PHP function, data.php, which fetches JSON data from an external server URL like such:

<?php
$url = "https://dev.externalserver.net/directory";
$content = file_get_contents($url);
echo json_encode($content);
?>

JSON数组中检索如下所示:

The JSON array retrieved looks like the following:

[ 
   { "name": "Not configured", 
     "mac_address": "1111c11c1111", 
     "online": "false", 
     "rate": "Not configured" },

   { "name": "Not configured", 
     "mac_address": "0000c00c0000", 
     "online": "false", 
     "rate": "Not configured" } 
]

我现在想写一个AJAX调用的PHP函数,遍历JSON数组,并在非JSON格式的浏览器中显示。我的AJAX code如下所示:

I'm now trying to write an AJAX call to that PHP function, iterate through the JSON array, and display it in the browser in non-JSON formatting. My AJAX code looks like the following:

$.ajax({ url: 'data.php',
         type: 'POST',
         dataType: 'json',
         success: function(output) {            
            $.each(output, function() { 
                $.each(this, function(key, value){
                    alert(key + " --> " + value); 
                });
            });
                                   }
});

我的问题是,code当前显示,显示像这样的阵列中的各个人物的警告框: 0 - &GT; [ 0 - &GT; 0 - &GT; { ...等等等等

My issue is that code is currently displaying alert boxes that show the individual characters within the array like such: 0 --> [ , 0 --> , 0 --> { ... etc etc

有没有使用json_en code()我是如何传递数据的问题;和数据类型:JSON还是的问题,我如何通过数组迭代解决?

Is there a problem with how I'm passing the data using json_encode(); and dataType: 'json' or does the issue resolve with how I'm iterating through the array?

感谢。

其他反应错过了偷偷摸摸的,但仍然明显的一点,那什么是从资源回来正在调查在PHP可能已经有效的JSON,并重新对其进行编码导致浏览器间preT它只是作为一个字符串。在这种情况下,JavaScript的没有机会。

Other responders missed the sneaky but still obvious bit, that what's coming back from the resource being polled in the PHP is probably already valid JSON, and re-encoding it is causing the browser to interpret it merely as a string. In this case, the javascript never had a chance.

删除json_en code()位在PHP,只是附和了回来,看看如果不提高的东西。

Remove the json_encode() bit in the PHP and just echo what comes back, and see if that doesn't improve things.