You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用jQuery的.each方法遍历AJAX返回的JSON数据以获取标题(title)与别名(slug)?附错误代码求助

Fixing Your AJAX Data Traversal Issue

Let's break down the problems in your code and fix them one by one:

Key Issues Identified

  1. Incorrect field access: Your data structure nests title and slug inside the fields object of each item, but you're trying to access them directly from the root item (value.title instead of value.fields.title).
  2. Invalid selector: $("trial") is missing a prefix—if your target element has an ID of trial, you need $("#trial"); if it's a class, use $(".trial").
  3. Unnecessary template syntax: The {{ }} around the title are leftover (unless you're using a templating engine like Handlebars, which doesn't seem to be the case here). Just insert the raw text directly.

Corrected Code

$(document).ready(function () { 
  $(".tag-nav-links").on("click", function (e) { 
    e.stopPropagation(); 
    return $.ajax({ 
      type: "POST", 
      url: "", // Ensure this points to your actual API endpoint
      dataType: "json", 
      data: { filter: `${e.target.textContent}` }, 
      success: function (data) { 
        var html = ""; 
        $.each(data, function (index, item) { 
          // Access title and slug from the nested fields object
          html += `<h4>${item.fields.title}</h4>`;
          // Optional: Add slug display if needed
          // html += `<p>Slug: ${item.fields.slug}</p>`;
        }); 
        $("#trial").append(html); // Fixed selector with ID prefix
      }, 
      error: function(xhr, status, error) {
        // Optional: Add error handling to debug request issues
        console.error("AJAX Request Failed:", error);
      }
    }); 
  }); 
});

Explanation of Changes

  • Field Access: Switched to item.fields.title to match your data structure (each entry's fields property contains the title and slug values).
  • Selector Fix: Added the # prefix to target the element with ID trial (adjust to .trial if it's a class instead).
  • Cleaner HTML Concatenation: Used ES6 template literals (backticks) for more readable code instead of messy string concatenation with +.
  • Error Handling: Added an error callback to help you debug if the AJAX request fails (useful for checking if your endpoint returns valid JSON).

Testing this code should now correctly loop through your AJAX response, extract each title, and append them to your target element.

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

火山引擎 最新活动