Javascript 迭代从php接收的json元素

Javascript 迭代从php接收的json元素,javascript,jquery,json,Javascript,Jquery,Json,我有一些JSON信息,来自PHPviaAjax {“5”:“rahul”,“26”:“karan”,“28”:“jatin”} 我想把键分开,它们是5,26,28 和单独的名称,分别是rahul、karan、jatin 我在java脚本中使用此代码。但并没有得到我想要的结果 for (var key in ajaxresponse) { if (ajaxresponse.hasOwnProperty(key)) { alert(key + " -> " +

我有一些JSON信息,来自
PHP
via
Ajax

{“5”:“rahul”,“26”:“karan”,“28”:“jatin”}

我想把键分开,它们是5,26,28 和单独的名称,分别是rahul、karan、jatin 我在
java脚本
中使用此代码。但并没有得到我想要的结果

for (var key in ajaxresponse) {
    if (ajaxresponse.hasOwnProperty(key)) 
    {
        alert(key + " -> " + JSON.stringify(ajaxresponse[key]));
    }
}

在一个非常简单的级别上,
for()
使用的是
ajaxresponse
,if/alert使用的是
response


如果您粘贴的代码是实际代码?如果是这样,那可能是你的问题。:)

在一个非常简单的级别上,
for()
使用的是
ajaxresponse
,而if/alert使用的是
response


如果您粘贴的代码是实际代码?如果是这样,那可能是你的问题。:)

跟随这篇文章,在jQuery的帮助下迭代json数据


跟随这篇文章,在jQuery的帮助下迭代json数据


只需使用两个阵列即可获得所需的内容:

var keys = [], vals = [], key,
ajaxresponse = JSON.parse(ajaxresponse);//parse JSON, which is quite important, too!
for (key in ajaxresponse)
{
    if (ajaxresponse.hasOwnProperty(key))
    {
        keys.push(key);
        vals.push(ajaxresponse[key]);
        console.log(key + '->' + ajaxresponse[key]);//no need to call JSON.stringify on a string
    }
}
console.log(keys.join(', '));//will list all keys, comma-separated
console.log(vals.join(', '));//ditto for values

只需使用2个数组,即可获得所需内容:

var keys = [], vals = [], key,
ajaxresponse = JSON.parse(ajaxresponse);//parse JSON, which is quite important, too!
for (key in ajaxresponse)
{
    if (ajaxresponse.hasOwnProperty(key))
    {
        keys.push(key);
        vals.push(ajaxresponse[key]);
        console.log(key + '->' + ajaxresponse[key]);//no need to call JSON.stringify on a string
    }
}
console.log(keys.join(', '));//will list all keys, comma-separated
console.log(vals.join(', '));//ditto for values

从你的解0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40{,,,,,,,,,,,,,,,2,8,如果您忘记了解析JSON,那么看起来:
ajaxresponse=JSON.parse(ajaxresponse)应该在这个代码之前,从您的解决方案0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,{但是我只需要5,26,28和rahul,karan,Jatin如果你忘了解析JSON,看起来:
ajaxresponse=JSON.parse(ajaxresponse)应位于此代码之前