我正在尝试与json合作,我几乎拥有我需要的东西.我正在显示正确的信息,但我必须将数组中的每个项目传递给变量,然后打印变量.我想显示每个数组中的所有项目.我正在使用的json数据来自一个发票应用程序(
www.curdbee.com),我正在尝试显示客户的每张发票.我想要显示的数据是每个订单项,订单项价格和总金额.这是我的代码:
$(document).ready(function() { $.getJSON('https://nspirelab.curdbee.com/invoices.json?api_token=__token__',function(data){ $.each(data,function(index,item){ var total = item.invoice.total_billed; var lineItemName1 = item.invoice.line_items[0].name_and_description; var lineItemName2 = item.invoice.line_items[1].name_and_description; var lineItemPrice1 = item.invoice.line_items[0].price; var lineItemPrice2 = item.invoice.line_items[1].price; $('#results').append('<div class="lineItem"><ul><li>' + lineItemName1 + lineItemPrice1 + '</li><li>' + lineItemName2 + lineItemPrice2 + '</li><li>' + total + '</li></ul></div>'); }); }); });
解决方法
嵌套循环(或者,在jQuery中,嵌套的$.each())将完成这项工作:
$.getJSON('https://nspirelab.curdbee.com/invoices.json?api_token=&client=104929',function(data){ $.each(data,item){ // create an empty ul (initially disconnected from the DOM) var $ul = $("<ul/>"); // iterate over the line items $.each(item.invoice.line_items,function(i,lineItem) { // create an li element with the line details and append // it to the ul $ul.append( $("<li/>").html(lineItem.name_and_description + lineItem.price) ); }); // add the totals to the end of the ul $ul.append( $("<li/>").html(item.invoice.total_billed) ); // create a new div,append the ul to it,and append the div to results $('#results').append( $('<div class="lineItem"/>').append($ul) ); }); });