我正在尝试使用 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, function(index, 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) );
});
});
关于javascript - 显示 json 数组中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10679355/