Javascript 在 $.ajax 中迭代 JSON 成功
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10990097/
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
Iterating through JSON within a $.ajax success
提问by Jason Wells
When a user clicks a button I want to return some data and iterate through the JSON so that I can append the results to a table row.
当用户单击按钮时,我想返回一些数据并遍历 JSON,以便将结果附加到表行。
At this point I am just trying to get my loop to work, here's my code.
在这一点上,我只是想让我的循环工作,这是我的代码。
My JSON is coming back as follows: {"COLUMNS":["username","password"],"DATA":[["foo", "bar"]]}
我的 JSON 返回如下: {"COLUMNS":["username","password"],"DATA":[["foo", "bar"]]}
$("#button").click(function(){
$.ajax({
url: 'http://localhost/test.php',
type: 'get',
success: function(data) {
$.each(data.items, function(item) {
console.log(item);
});
},
error: function(e) {
console.log(e.message);
}
});
});
I'm getting a jQuery (line 16, a is not defined) error. What am I doing wrong?
我收到 jQuery(第 16 行,未定义)错误。我究竟做错了什么?
回答by Shyju
Assuming your JSON
is like this
假设你JSON
是这样的
var item= {
"items": [
{ "FirstName":"John" , "LastName":"Doe" },
{ "FirstName":"Anna" , "LastName":"Smith" },
{ "FirstName":"Peter" , "LastName":"Jones" }
]
}
You can query it like this
你可以这样查询
$.each(item.items, function(index,item) {
alert(item.FirstName+" "+item.LastName)
});
Sample : http://jsfiddle.net/4HxSr/9/
示例:http: //jsfiddle.net/4HxSr/9/
EDIT : As per the JSON OP Posted later
编辑:根据稍后发布的 JSON OP
Your JSON
does not have an items, so it is invalid.
您JSON
没有商品,因此无效。
As per your JSON like this
根据你的 JSON 这样
var item= { "COLUMNS": [ "username", "password" ],
"DATA": [ [ "foo", "bar" ] ,[ "foo2", "bar2" ]]
}
You should query it like this
你应该这样查询
console.debug(item.COLUMNS[0])
console.debug(item.COLUMNS[1])
$.each(item.DATA, function(index,item) {
console.debug(item[0])
console.debug(item[1])
});
Working sample : http://jsfiddle.net/4HxSr/19/
工作示例:http: //jsfiddle.net/4HxSr/19/
回答by Sp4cecat
You need to add:
您需要添加:
dataType: 'json',
.. so you should have:
..所以你应该有:
$("#button").click(function(){
$.ajax({
url: 'http://localhost/test.php',
type: 'get',
dataType: 'json',
success: function(data) {
$.each(data.COLUMNS, function(item) {
console.log(item);
});
},
error: function(e) {
console.log(e.message);
}
});
});
.. as well as ensuring that you are referencing COLUMNS in the each statement.
.. 以及确保您在每个语句中引用 COLUMNS。
getJson is also another way of doing it..
getJson 也是另一种方法。