英文:
Jquery undefined variable when iterating
问题
这是您提供的内容的翻译:
我有一个非常简单的jQuery HTML网站,它连接到后端并应该列出一个数组。我尝试了各种方法来解决在迭代对象并访问它们的属性时显示“undefined”的问题。在调试器中,我没有看到明显的问题,数组似乎看起来很正常。肯定有一些重要的东西我遗漏了。我做错了什么?
这是服务器的示例响应:
[
  {
    "id": "123",
    "name": "123",
    "description": "A long description",
    "image": ""
  }
]
这是HTML代码:
<!DOCTYPE html>
<html>
<head>
  <title>JSON数据示例</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <h1>JSON数据示例</h1>
  <div id="data"></div>
  <script>
    $(document).ready(function() {
      // 发送到服务器的AJAX请求
      $.ajax({
        url: "http://localhost:4711",
        method: "GET",
        dataType: "json",
        success: function(response) {
          displayData(response);
        },
        error: function() {
          alert("从服务器检索数据时出错。");
        }
      });
    });
    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>
您提供了示例调试器信息(仅用于显示对象存在但在评估时未定义的情况)。
英文:
I have a very simple jquery HTML site which connects to a backend and should list an array. I've tried various ways to fix showing "undefined" when iterating through the objects and accessing their properties. I do not see anything obviously wrong in the debugger, the array seems to look just fine. There must be something essential I'm missing. What am I doing wrong?
This is the server's example response:
[
{
  "id": "123",
  "name": "123",
  "description": "A long description",
  "image": ""
}
]
This is the HTML code:
<!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() {
      // Make an AJAX request to the server
      $.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>
I've created a fiddle here: https://jsfiddle.net/7vcu5hp3/
Example Debugger Info (just to show that the object exists but will be undefined when evaluated):
答案1
得分: 1
如果您绝对必须将它转换为一个jQuery对象(在这种情况下没有必要),您将需要将[0]添加到$(data[i]),这样它就变成了$(data[i])[0]。
由于您正在使用jQuery,您可以轻松地使用$.each来遍历数组,不需要使用for循环。
let data = [{
  "id": "123",
  "name": "123",
  "description": "A long description",
  "image": ""
}]
function displayData(data) {
  var output = "";
  $.each(data, function (k, 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>";
  })
  document.getElementById("data").innerHTML = output;
}
displayData(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="data"></div>
注意:我保留了您的注释和HTML部分,没有进行翻译。
英文:
If you absolutely have to convert it to a jquery object (which there is no reason for in this case), you will need to add [0] to $(data[i]) so its $(data[i])[0].
Since you are using jQuery you can easily loop through arrays with $.each. you don't need a for loop
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let data = [{
  "id": "123",
  "name": "123",
  "description": "A long description",
  "image": ""
}]
function displayData(data) {
  var output = "";
  $.each(data,function(k,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>";
  })
  document.getElementById("data").innerHTML = output;
}
displayData(data)
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="data"></div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论