[英]Display all items in a json array
I am trying to work with json and I almost have what I need. 我正在尝试与json合作,我几乎拥有我需要的东西。 I am getting the correct info to display but I am having to pass each item of an array into a variable and then print the variable.
我正在显示正确的信息,但我必须将数组中的每个项目传递给变量,然后打印变量。 I would like to display all of the items in each array.
我想显示每个数组中的所有项目。 The json data I am working with is from an invoicing app ( www.curdbee.com ) and I am trying to show each invoice for a client.
我正在使用的json数据来自一个发票应用程序( www.curdbee.com ),我正在尝试为客户显示每张发票。 The data that I want to show is each line item, the line item price, and the total amount.
我想要显示的数据是每个订单项,订单项价格和总金额。 Here is my code:
这是我的代码:
$(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>');
});
});
});
A nested loop (or, in jQuery, a nested $.each()
) will do the job: 嵌套循环(或者,在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) );
});
});
There are a ridiculous number of libraries out there to make things like this easier. 有一些荒谬的图书馆可以让这样的事情变得更容易。 Do a search for "javascript templates" to see what you've been missing and to learn about the various libraries you can choose between for this.
搜索“javascript模板”以查看您所缺少的内容,并了解您可以选择的各种库。
如果我理解你的问题,我认为你正在寻找的是某种迭代机制,尝试下划线.js 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.