7

私は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>');
        });

    });

});
4

3 に答える 3

5

ネストされたループ (または、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) );
   });
});
于 2012-05-21T04:09:57.577 に答える
0

あなたの質問を正しく理解していれば、あなたが探しているのはある種の反復メカニズムだと思います。 underscore.jsを試してください。

于 2012-05-21T04:09:31.457 に答える
0

このようなことを簡単にするために、ばかげた数のライブラリがあります。「javascript テンプレート」を検索して、不足しているものを確認し、このために選択できるさまざまなライブラリについて学びます。

于 2012-05-21T04:04:34.610 に答える