如何使用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
- Incorrect field access: Your data structure nests
titleandsluginside thefieldsobject of each item, but you're trying to access them directly from the root item (value.titleinstead ofvalue.fields.title). - Invalid selector:
$("trial")is missing a prefix—if your target element has an ID oftrial, you need$("#trial"); if it's a class, use$(".trial"). - 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.titleto match your data structure (each entry'sfieldsproperty contains the title and slug values). - Selector Fix: Added the
#prefix to target the element with IDtrial(adjust to.trialif 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
errorcallback 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




