在JQuery中使用foreach解析JSON
这是我现在通过JQuery执行AJAX的代码:在JQuery中使用foreach解析JSON,jquery,Jquery,这是我现在通过JQuery执行AJAX的代码: $.ajax({ type: "POST", url: linktopage, contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { $.each(dat
$.ajax({
type: "POST",
url: linktopage,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (index, item) {
alert(item.productId);
});
},
error: function (xhr, status, error) {
}
});
如果index=d和item=“[{“productId”:5284598},{“productId”:5790923}]”但是警报(item.productId)未定义,我如何访问每个productId?在您的示例中,有一个项目数组。您必须重复该操作才能获得productId
for( var i = 0; i < item.length; i++ ){
console.log(item[i].productId);
}
在迭代之前。(有关解析的更多信息:)
如下所示(您还可以先测试它是否是字符串):
在您的案例中,数据是一个字符串条目。因此,您必须首先将其解析为JSON。 将您的代码更新到此位置
$.ajax({
type: "POST",
url: linktopage,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dta = $.parseJSON(data);
$.each(dta , function (index, item) {
alert(item.productId);
});
},
error: function (xhr, status, error) {
}
});
如果您能给我们一个返回的JSON数据的示例,那就容易多了。这是返回的JSON数据:“[{“productId”:5284598},{“productId”:5790923}]”在这种情况下,您应该使用的是:如果您
console.log(data)
,并且它是一个字符串而不是一个对象,是的,Travis收到的JSON是一个字符串,我需要先解析它,然后才能使用它。谢谢你的帮助!:)
$.ajax({
type: "POST",
url: linktopage,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if( typeof data == "string" )data = JSON.parse(data);
$.each(data, function (index, item) {
alert(item.productId);
});
},
error: function (xhr, status, error) {
}
});
$.ajax({
type: "POST",
url: linktopage,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dta = $.parseJSON(data);
$.each(dta , function (index, item) {
alert(item.productId);
});
},
error: function (xhr, status, error) {
}
});