2016-04-15 11 views
0

jsonのデータを含むテーブルを作成したいのですが、データやその他のものを含む行を作成できるようにjqueryコードを変更する必要がありますか?json/jqueryのデータを使ってテーブルを作成するには?

私は私のデータでテーブルを水平に作成すると、<th>タグが行としてcssでインラインで表示されますが、jsonでインポートされたデータは垂直方向に1列に表示されます。

のjQuery:

$(document).ready(function() { 
    $.ajax({ 
     url: 'weather.json', 
     type: 'GET', 
     dataType: 'json', // Returns JSON 
     success: function(response) { 
      var sTxt = ''; 
      $.each(response, function(index, weatherElement) { 
       sTxt += '<tr><td>' + weatherElement.city+'</td></tr>'; 
       sTxt += '<tr><td>' + weatherElement.current_condition+'</td></tr>'; 
       sTxt += '<tr><td>' + weatherElement.temperature+'</td></tr>'; 
       sTxt += '<tr><td>' + weatherElement.wind_speed+'</td></tr>'; 
       sTxt += '<tr><td>' + weatherElement.wind_direction+'</td></tr>'; 
       sTxt += '<tr><td>' + weatherElement.wind_chill_factor+'</td></tr>'; 
      }); 
      $('#weatherlist').append(sTxt); 
     }, 
     error: function() { 
      $('#info').html('<p>An error has occurred</p>'); 
     } 
    }); 
}); 

HTML:

<!DOCTYPE html> 
    <html> 

    <head> 
     <title>Ajax and json Data</title> 
     <meta charset="UTF-8"> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> 
     <script src="weather.js" type="text/javascript"></script> 
     <link rel="stylesheet" type="text/css" href="styles.css"> 
    </head> 

     <body> 
      <header> 
       <h1>British and Irish Counties - Weather Data</h1> 
      </header> 
      <section> 
       <table id="weatherlist"> 
        <tr> 
         <th>City</th> 
         <th>Conditions</th> 
         <th>Temperature</th> 
         <th>Wind Speed</th> 
         <th>Wind Direction</th> 
         <th>Wind Chill Factor</th> 
        </tr> 
       </table> 
       <div id="updatemessage"></div> 
       <p id="info"></p> 
      </section> 
      <footer> 
      </footer> 
     </body> 

     </html> 

答えて

5

あなたのテーブルの行が正しくフォーマットされていません。すべてのtd要素を単一のtr要素にラップする必要があります。

sTxt += '<tr><td>' + weatherElement.city+'</td></tr>'; 
sTxt += '<tr><td>' + weatherElement.current_condition+'</td></tr>'; 
sTxt += '<tr><td>' + weatherElement.temperature+'</td></tr>'; 
sTxt += '<tr><td>' + weatherElement.wind_speed+'</td></tr>'; 
sTxt += '<tr><td>' + weatherElement.wind_direction+'</td></tr>'; 
sTxt += '<tr><td>' + weatherElement.wind_chill_factor+'</td></tr>'; 

これに:この

変更

sTxt += '<tr>'; 
sTxt += '<td>' + weatherElement.city+'</td>'; 
sTxt += '<td>' + weatherElement.current_condition+'</td>'; 
sTxt += '<td>' + weatherElement.temperature+'</td>'; 
sTxt += '<td>' + weatherElement.wind_speed+'</td>'; 
sTxt += '<td>' + weatherElement.wind_direction+'</td>'; 
sTxt += '<td>' + weatherElement.wind_chill_factor+'</td>'; 
sTxt += '</tr>'; 
関連する問題