JavaScript & jQuery 在循环中解析 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15387657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:37:06  来源:igfitidea点击:

JavaScript & jQuery parse JSON in loop

javascriptjqueryhtmljson

提问by Alias

Sorry about asking this, I can't get it to work even with looking at other questions...

很抱歉问这个问题,即使查看其他问题我也无法让它工作......

I have a JSON output in "json.php", for example:

我在“json.php”中有一个 JSON 输出,例如:

    [
       {"serverid":"1","servername":"Server One"},
       {"serverid":"2","servername":"Server Two"}
    ]

I have a script, to grab the data & parse it into a variable

我有一个脚本,用于获取数据并将其解析为变量

var servers;
jQuery.get('json.php', function(data) {
     servers =    JSON.parse(data);
     jQuery('#servers').servers.servername
});

I have a div to output the results to:

我有一个 div 将结果输出到:

<div id="servers"></div>

Whatever I try, I always get some kind of

无论我尝试什么,我总能得到某种

"Uncaught TypeError: Cannot read property 'servername' of undefined" error.

“未捕获的类型错误:无法读取未定义的属性 'servername'”错误。

I'd also like to look around the results, however I can't even get it to print atm.

我也想看看结果,但是我什至无法打印 atm。

Again sorry for another question like this

再次为这样的另一个问题感到抱歉

回答by mattytommo

Don't you mean something like this? the jQuery object (which is a reference to your div) knows nothing about servername. Also, you'll need to iteratethrough the array of items in order to get them all:

你不是说这样的吗?jQuery 对象(它是对 div 的引用)对servername. 此外,您需要遍历项目数组以获取所有项目:

servers = $.parseJSON(data);

$.each(servers, function(index, value) {
    $("#servers").text($("#servers").text() + " " + value.servername);
});

Fiddle: http://jsfiddle.net/H2RC2/1/

小提琴:http: //jsfiddle.net/H2RC2/1/

回答by Alberto De Caro

The error message is all you need. The jQuery('#servers')wrap the #servers div in the jQuery object. And this object has got no property such as servers.

错误消息就是您所需要的。该jQuery('#servers')包装的#servers div的jQuery对象中。并且这个对象没有诸如servers.

Rather you could use:

相反,您可以使用:

    var servers = JSON.parse(data);
    var res = '';
    for(var i = 0; i<servers.length; i++){
        res = res + '<p>' + servers[i].servername +'</p>';
    }

    $('#servers').append(res);