使用jQuery访问多维JSON数组中的数据 [英] Accessing data in a multidimensional JSON array with jQuery

查看:120
本文介绍了使用jQuery访问多维JSON数组中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试研究如何在基本上多维的JSON数组中访问数据。

I am trying to work out how to access data in an essentially multidimensional JSON array.

我的jQuery AJAX请求如下所示:

My jQuery AJAX request looks like this:

 $("#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'
  });
});

这就是我要回来的。用户帐户详细信息,以及他们针对其帐户的产品列表。

This is what i am getting back. User account details, plus a list of products they have against their account.

{
    "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访问第一维中的所有内容,但我不知道如何我需要索引下一个维度。显然我想以某种方式显示每个产品。

As you can see, i am alerting the first name, which is fine. I can access everything in the first dimension by using data.key but i'm not sure how then i need to index the next dimension. Obviously I would like to display each of the products somehow.

建议是最受欢迎的。

推荐答案

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

Inside your success function you can treat the JSON data as a JavaScript object. You can access the product array and objects inside it like this:

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

alert <替换 console.log / code>如果你不知道什么是控制台。

Replace console.log with alert if you do not know what console is.

这篇关于使用jQuery访问多维JSON数组中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆