使用ajax调用从JSON获取数据到HTML表



我想从服务器获取数据并传输到HTML表。服务器包含如下数组列表

[{"date":"19/08/2020","weather":"Sunny","temperature":30,"temp_unit":"celcius"}, 
{"date":"30/08/2020","weather":"Sunny","temperature":31,"temp_unit":"celcius"}, 
{"date":"21/08/2020","weather":"Cloudy","temperature":29,"temp_unit":"celcius"}, 
{"date":"22/08/2020","weather":"Sunny","temperature":29,"temp_unit":"celcius"}, 
{"date":"23/08/2020","weather":"Sunny","temperature":31,"temp_unit":"celcius"}, 
{"date":"24/08/2020","weather":"Sunny","temperature":30,"temp_unit":"celcius"}, 
{"date":"25/08/2020","weather":"Cloudy","temperature":28,"temp_unit":"celcius"}, 
{"date":"26/08/2020","weather":"Cloudy","temperature":27,"temp_unit":"celcius"}, 
{"date":"27/08/2020","weather":"Sunny","temperature":29,"temp_unit":"celcius"}, 
{"date":"28/08/2020","weather":"Sunny","temperature":28,"temp_unit":"celcius"}, 
{"date":"29/08/2020","weather":"Cloudy","temperature":28,"temp_unit":"celcius"}, 
{"date":"30/08/2020","weather":"Sunny","temperature":31,"temp_unit":"celcius"}]

我已经创建了代码如下,以获取使用ajax调用的数据。但是对于所有值,表显示为未定义。

//implement css in this files
import './style.css';
//jquery already imported
import $ from 'jquery';
// ajax to load
// do table data binding here using data from variable resultArr
var myArray = []
$.ajax({
method: 'GET',
url: 'https://www.seetrustudio.com/data.php',
success: function(response) {
myArray = response
buildTable(myArray)
console.log(myArray)
}
})
function buildTable(data) {
var table = document.getElementById('myTable')
for (var i = 0; i < data.length; i++) {
var row = `<tr>
<td>${data[i].date}</td>
<td>${data[i].weather}</td>
<td>${data[i].temperature}</td>
<td>${data[i].temp_unit}</td>
</tr>`
table.innerHTML += row
}
}

问题是如何修复它并将列表正确地传递到HTML表中?

问题是响应是原始文本,所以您需要对响应进行JSON.parse

$.ajax({
method: 'GET',
url: 'https://www.seetrustudio.com/data.php',
success: function(response) {
buildTable(JSON.parse(response));  <---- this line is required.
}
})
function buildTable(data) {
var table = document.getElementById('myTable')
for (var i = 0; i < data.length; i++) {
var row = `<tr>
<td>${data[i].date}</td>
<td>${data[i].weather}</td>
<td>${data[i].temperature}</td>
<td>${data[i].temp_unit}</td>
</tr>`
table.innerHTML += row
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='myTable'></table>

相关内容

  • 没有找到相关文章

最新更新