1

私は JavaScript にあまり強くなく、ajax リクエストから返されたデータをループするのに苦労しています。

私が望むのは、ループが配列を 10 回通過し、テーブルに行を生成することです。

ただし、機能していないようです。これがコード全体です。

$.getJSON('charts_ajax.php',{a : 'terms'},function(data){
   if(data){
     var tableTop = '<tbody><tr><th width="5%">#</th><th width="65%">Search Terms</th><th width="15%">Visits</th></tr>';

     var si = 1;
     $.each(data, function(index, value) {
         var tableInner = '<tr><td>1</td><td>' + data[si][0]  + '</td><td>307</td></tr>';
         si++;
     });

     var tableBottom = '</tbody></table>';

     $('#terms-table').html(tableTop + tableInner + tableBottom);

   }

});

何も表示されません。console.log(data) を取得すると、次のようになります。

0: [Terms, Visits]
1: [radio fm, 150]
2: [radio fm grimsby, 25]
3: [radio , 10]
4: [radio fm radio, 9]
5: [radio .co.uk, 9]
6: [grimsby rugby club, 8]
7: [radio radio, 7]
8: [radio radio grimsby, 5]
9: [radio , 5]
10: [radio station, 4]

私はここで完全な初心者ですか?

みんな、事前に乾杯:)

4

2 に答える 2

1

したがって、これを見ている人にとっては、少し助けて問題を解決しました.tableInner変数を繰り返し、追加していないことを指摘してくれた@remyabelに感謝します。

これが解決策です(コメント付きのフルコード):

/// Create the Request
$.getJSON('charts_ajax.php',{a : 'terms'},function(data){
   // Check that there is data coming back from the request
   if(data){
       //Start the table html
       var tableTop = '<tbody><tr><th width="5%">#</th><th width="65%">Search Terms</th><th width="15%">Visits</th></tr>';
       var tableInner = '';

       //For each of the items in data Create an inner row of the table
       $.each(data, function(index, row) {
          if(index !== 0){
          tableInner += '<tr><td>' + index + '</td><td>' + row[0]  + '</td><td>' + row[1] + '</td></tr>';
          }
       });

      //close the table
      var tableBottom = '</tbody></table>';

     // Find the table by id and insert the html. 
     $('#terms-table').html(tableTop + tableInner + tableBottom);

     }

});
于 2013-11-06T10:13:15.827 に答える
1

各呼び出しで tableInner を再割り当てしています。代わりにこれをするつもりですか?

var tableInner = '';
$.each(data, function(index, value) {
         tableInner += '<tr><td>1</td><td>' + data[si][0]  + '</td><td>307</td></tr>';
         si++;
});

配列が次のようになっていると仮定します。

var data = [
  ["Terms", "Visits"],
["radio fm", 150],
["radio fm grimsby", 25],
["radio ", 10],
["radio fm radio", 9],
["radio .co.uk", 9],
["grimsby rugby club", 8],
["radio radio", 7],
["radio radio grimsby", 5],
["radio ", 5],
 ["radio station", 4]
  ];

次に、これ:

$.each(data, function(index, value) {
  var part1 = value[0];
  var part2 = value[1];
  console.log(part1 + ' ' + part2);
});

出力:

"Terms Visits"
"radio fm 150"
"radio fm grimsby 25"
"radio  10"
"radio fm radio 9"
"radio .co.uk 9"
"grimsby rugby club 8"
"radio radio 7"
"radio radio grimsby 5"
"radio  5"
"radio station 4"

データを反復処理する方法にエラーがあります。

于 2013-11-06T09:44:07.713 に答える