You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过AJAX获取JSON数据渲染HTML表格时出现undefined该如何修复

问题原因

服务端返回的是JSON格式字符串,当前代码没有将字符串转换为可直接读取属性的JavaScript对象数组,直接读取对象属性就会返回undefined。

修复方案

方案1:指定AJAX响应的dataType为JSON

在$.ajax配置中新增dataType: 'json'参数,jQuery会自动将返回的JSON序列化为JS对象:

//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',
  dataType: 'json', // 新增这一行,指定返回格式为JSON
  success: function(response) {
    myArray = response
    buildTable(myArray)
    console.log(myArray)
  }
})

function buildTable(data) {
  var table = document.getElementById('myTable')
  // 渲染前先清空原有内容,避免重复拼接
  table.innerHTML = ''
  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
  }
}

方案2:手动解析JSON字符串

如果不方便加dataType配置,也可以在success回调中手动用JSON.parse()转换响应内容:

success: function(response) {
  myArray = JSON.parse(response) // 手动转成JS对象数组
  buildTable(myArray)
  console.log(myArray)
}

额外校验点

请确认你的HTML代码中存在对应ID的表格节点,结构示例如下:

<table>
  <thead>
    <tr>
      <th>日期</th>
      <th>天气</th>
      <th>温度</th>
      <th>温度单位</th>
    </tr>
  </thead>
  <tbody id="myTable"></tbody>
</table>

内容的提问来源于stack exchange,提问作者Nur Azrina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 09:36:04