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

使用jQuery遍历后端数组时属性显示undefined的问题求助

问题:遍历后端返回的对象时属性显示undefined,该怎么解决?

我有一个简单的jQuery HTML站点,连接后端展示数组数据。尝试了多种方法解决遍历对象访问属性时显示“undefined”的问题,调试器里数组看起来完全正常,但就是拿不到属性值,请问哪里出错了?

服务器示例响应

[
{
  "id": "123",
  "name": "123",
  "description": "A long description",
  "image": ""
}
]

我的HTML代码

<!DOCTYPE html>
<html>
<head>
  <title>JSON Data Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <h1>JSON Data Example</h1>

  <div id="data"></div>

  <script>
    $(document).ready(function() {
      $.ajax({
        url: "http://localhost:4711",
        method: "GET",
        dataType: "json",
        success: function(response) {
          displayData(response);
        },
        error: function() {
          alert("Error retrieving data from the server.");
        }
      });
    });

    function displayData(data) {
      var output = "";
      for (var i = 0; i < data.length; i++) {
        var $obj = $(data[i]);
        output += "<div>";
        output += "<h2>ID: " + $obj.id + "</h2>";
        output += "<p>Name: " + $obj.name + "</p>";
        output += "<p>Description: " + $obj.description + "</p>";
        //output += "<img src='" + $obj.image + "' alt='Image'>";
        output += "</div>";
      }
      document.getElementById("data").innerHTML = output;
    }
  </script>
</body>
</html>

错误原因

你把后端返回的普通JavaScript对象用$(data[i])转换成了jQuery对象,但jQuery对象并不会直接暴露原对象的属性,所以访问$obj.id这类属性时会得到undefined。

修复方法

直接使用原JavaScript对象,不需要包一层jQuery。修改displayData函数:

function displayData(data) {
  var output = "";
  for (var i = 0; i < data.length; i++) {
    var obj = data[i];
    output += "<div>";
    output += "<h2>ID: " + obj.id + "</h2>";
    output += "<p>Name: " + obj.name + "</p>";
    output += "<p>Description: " + obj.description + "</p>";
    //output += "<img src='" + obj.image + "' alt='Image'>";
    output += "</div>";
  }
  document.getElementById("data").innerHTML = output;
}

更简洁的写法(使用jQuery的each遍历)

function displayData(data) {
  var output = "";
  $.each(data, function(index, obj) {
    output += "<div>";
    output += "<h2>ID: " + obj.id + "</h2>";
    output += "<p>Name: " + obj.name + "</p>";
    output += "<p>Description: " + obj.description + "</p>";
    //output += "<img src='" + obj.image + "' alt='Image'>";
    output += "</div>";
  });
  $("#data").html(output);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:59:55