我试图找出如何访问基本上多维JSON数组中的数据.
我的jQuery AJAX请求如下所示:
$("#login-form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',url: '/ajax/login',data: 'email='+$("#email").val()+'&password='+$("#password").val(),success: function(data){
// FIRE ALERT HERE
alert(data.firstname);
},dataType: 'json'
});
});
这就是我要回来的.用户帐户详细信息,以及他们针对其帐户的产品列表.
{
"logged_in":true,"firstname":"Joe","surname":"Bloggs","Full_name":"Joe Bloggs","email":"email@website.com","phone":"+123456789","website":"","age":"26-35","street":"1 Street Ave","city":"Townland","state":"NA","postcode":"1234","country":"Australia","products":2,"0":{
"product_no":"1087","customer":"2","bought_from":"1","date_of_purchase":"2011-04-08","method":"instore","invoice":"0","current":"1"
},"1":{
"product_no":"24","current":"1"
}
}
正如你所看到的,我正在警告第一个名字,这很好.我可以通过使用data.key访问第一维中的所有内容,但我不知道如何我需要索引下一个维度.显然我想以某种方式展示每个产品.
建议是最受欢迎的.
最佳答案
在您的成功函数中,您可以将JSON数据视为JavaScript对象.您可以像这样访问其中的产品数组和对象:
原文链接:https://www.f2er.com/jquery/427941.htmlconsole.log(data.products + " product(s) in data"); // data.products is 2 (integer)
for(var i = 0; i < data.products; i++) { //
var product = data[i.toString()]; // 0.toString() is "0"
// data["0"] is what you want
// now product points to the property "0"
console.log(product.product_no); // so you can use product.xxx
// or product["xxx"]
} // likewise for "1","2","3" and so on
如果您不知道控制台是什么,请将alert.log替换为alert.