javascript 使用 jQuery 处理 JSON 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5724566/
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
Handling JSON Object With jQuery?
提问by Cheyne
I'm having trouble handling a JSON object that I'm getting back from an AJAX request.
我在处理从 AJAX 请求返回的 JSON 对象时遇到问题。
It's a simple flat JSON object, and all I want to do is write the responses back onto the page.
这是一个简单的平面 JSON 对象,我想做的就是将响应写回页面。
Can anyone point out how to loop over these objects and output the values? I just keep getting [undefined]or [object]written
谁能指出如何遍历这些对象并输出值?我只是不断地得到[undefined]或[object]写作
Code here:
代码在这里:
$.ajax({
type: "POST",
url: "func/chatResponse.php",
data: dataString,
success: function() {
$.getJSON('func/chatResponse.php?a=jsonLatest', function(data) {
$.each(data, function(index) {
//items.push('<li id="' + key + '">' + val + '</li>');
$('body').append('<li id="' + data.user + '">' + data.user + '</li>');
alert(data);
});
});
alert("done");
}
});
JSON sample here
JSON 示例在这里
[
{"user":"someguy","message":"my message","timestamp":"2011-04-19 17:26:09"},
{"user":"Cheyne","message":"Hey There ... Nice site","timestamp":"2011-04-19 17:26:09"}
]
回答by David Tang
datais the array, while you want the items inside the array.
data是数组,而您想要数组内的项目。
$.eachdoesn't change datato become the items, instead it passes individual items as the second parameter to the function you supply:
$.each不会更改data为项目,而是将单个项目作为第二个参数传递给您提供的函数:
$.each(data, function (index, item) {
// Use item in here
$('body').append('<li id="' + item.user + '">' + item.user + '</li>');
});
Alternatively, you can use data[index]:
或者,您可以使用data[index]:
$.each(data, function (index) {
// use data[index] in here
$('body').append('<li id="' + data[index].user + '">' + data[index].user + '</li>');
});
By the way, avoid ugly string concatenation with:
顺便说一句,避免丑陋的字符串连接:
$('<li>', {id: item.user, text: item.user}).appendTo('body');
回答by Ry-
What you want is
你想要的是
$.each(data, function(index) {
//items.push('<li id="' + key + '">' + val + '</li>');
$('body').append('<li id="' + data[index].user + '">' + data[index].user + '</li>');
alert(data);
});

