2013-02-28 78 views
1

Javascript to this here。我在使用JQuery解析某些JSON时遇到了一些麻烦。我相信这是由我的JSON结构决定的,但是我正在使用这些脚本来处理其他服务,所以我们不需要改变那里的结构。如何在循环中解析JSON

我的JSON是如下

{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack Black","auto_id":"22"}]} 

我会非常喜欢用CUSTOMER_NAME来填充ListView和我也想保存auto_id地方(也许本地存储),所以如果选择我可以提出相关数据。

如果有人可以帮我构建一个循环来解析这个JSON,我会非常感激。

回答

1

您可以按照以下步骤操作。

$('#home').live('pageshow', function(){ 
    // creating object 
    var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack Black","auto_id":"22"}]}'); 

    // creating html string 
    var listString = '<ul data-role="listview" id="customerList">'; 

    // running a loop 
    $.each(customerList.customerInAccount, function(index,value){ 
    listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>'; 
    }); 
    listString +='</ul>'; 

    console.log(customerList); 

    //appending to the div 
    $('#CustomerListDiv').html(listString); 

    // refreshing the list to apply styles 
    $('#CustomerListDiv ul').listview(); 

    // getting the customer id on the click 
    $('#customerList a').bind('click',function(){ 
    var customerID = $(this).data('cusid'); 
    alert(customerID); 
    }); 
}); 

您可以在此处查看当前工作的小提琴。 http://jsfiddle.net/amEge/3/

+0

前两个答案很好,向我解释很多,这让我能够访问和填充我的列表,但您的答案更进一步,并告诉我如何访问id变量,这是非常有用的,非常感谢大家。 – user1668630 2013-02-28 14:39:47

+0

很高兴帮助你:) – 2013-03-01 05:41:36

3

您可以使用jQuery轻松解析它。

$.parseJSON(data); 

试试这个:

var json = $.parseJSON(data); 
for(var i=0; i<json.customerInAccount.length; i++){ 
    // do your stuff here.. 
} 

如果您有任何问题,请让我知道

1

使用这样

var value=yourJsonString 
var results=JSON.parse(value); 

$.each(results.customerInAccount,function(i,item){ 
// do with item 
alert( item.customer_name); 
}); 

工作演示:JSON parse with loop