使用jQuery访问多维JSON数组中的数据

我试图找出如何访问基本上多维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", "customer":"2", "bought_from":"1", "date_of_purchase":"2011-04-08", "method":"instore", "invoice":"0", "current":"1" } } 

正如你所看到的,我正在警告第一个名字,这很好。 我可以通过使用data.key访问第一维中的所有内容,但我不知道如何我需要索引下一个维度。 显然我想以某种方式展示每个产品。

建议是最受欢迎的。

在您的成功函数中,您可以将JSON数据视为JavaScript对象。 您可以像这样访问其中的产品数组和对象:

 console.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 

如果您不知道控制台是什么,请将console.log替换为alert

可以通过data[iProductIndex.toString()]成员访问每个产品详细信息。 数据存储在data["0"]data["1"] ,因此要访问它们,您需要将整数值转换为字符串。 不幸的是,您将无法使用$.each循环,因为“0”和“1”是单独的成员对象。 用于与iProductIndex循环。

提供的数据不允许您的答案,Salman A.请参阅JSON Arrays进行数组定义,让它按照您的方式工作,它必须被定义为

 {"products" : [ {"product_no":"1087", "customer":"2", "bought_from":"1", "date_of_purchase":"2011-04-08", "method":"instore", "invoice":"0", "current":"1"} ] } 

至OP:alert(data [“0”]。product_no); 警报(数据[ “1”] [ “date_of_purchase”]);

试试这个