将原生JavaScript Ajax代码转换为jQuery时遇错误,求解决方案
Let's break down your issues one by one and fix the jQuery conversion step by step:
Key Issues & Fixes
displayOutput is not definedError
The problem is you're using aconstarrow function fordisplayOutput, which doesn't get hoisted like function declarations. When your AJAX success callback runs, the function hasn't been defined yet (since it's placed after the$(document).ready()block).- Fix: Move the
displayOutputdefinition inside thereadyfunction, or use a function declaration (function displayOutput() {}) which gets hoisted.
- Fix: Move the
Cannot read property 'forEach' of undefined
When you setdataType: 'JSON'in jQuery's AJAX, jQuery automatically parses the server response into a JavaScript object/array. Your code incorrectly tries to accessresponse.responseText(this is a property of the rawXMLHttpRequestobject, not jQuery's processed response). This makesdataundefined, so callingforEachon it fails.- Fix: Use the
responseparameter directly as your parsed data.
- Fix: Use the
DOM Element vs jQuery Object Mismatch
$('.ajax')[0]returns a raw DOM element, but.html()is a jQuery method. Calling it on a DOM element will throw an error.- Fix: Use jQuery's built-in methods like
.first()or.eq()to get jQuery objects, or wrap the DOM element in$()to convert it.
- Fix: Use jQuery's built-in methods like
Uncaught ReferenceError: data is not defined
Theconsole.log(data)outside thereadyblock is trying to access a variable that only exists inside the AJAX success callback (it's scoped locally there).- Fix: Move the
console.loginside the success callback, or remove it.
- Fix: Move the
Corrected Full Code
$(document).ready(function() { // Define displayOutput first so the AJAX callback can access it const displayOutput = (games, hasCheckbox) => { let output = ""; let x = 0; games.forEach(game => { x++; output +=` <li> <div> <input id="togg${x}" type="checkbox"> <label for="togg${x}" class="${hasCheckbox ? 'visible' : 'invisible'}">Compare</label> </div> </li> <li> <a href="#"> <img class="frontGames" src="${game.image}"> <p> <b>Name:</b>${game.Name}<br> <b>Release Date:</b>${game.ReleaseDate}<br> <b>Genres:</b>${game.Genres}<br> <b>Retail Price:</b>${game.RetailPrice}<br> <b>Rating:</b>${game.Rating}<br> </p> </a> </li>`; }); return output; }; $.ajax({ url: "data/games.json", dataType: 'json', success: function(data){ // Use jQuery methods to get elements reliably const $ul1 = $('.ajax').first(); const $ul2 = $('.ajaxCheck').eq(0); const $ul3 = $('.ajaxCheck').eq(1); // Check if the element exists using .length (more reliable than truthy check) if ($ul1.length) { $ul1.html(displayOutput(data, false)); } else { $ul2.html(displayOutput(data, true)); $ul3.html(displayOutput(data, true)); } // Log data here if needed console.log(data); }, error: function(xhr, status, error) { // More detailed error logging for debugging console.error('Request failed:', status, error); } }); });
Extra Optimizations
- I removed unused
newReleasesandcomingSoonvariables to clean up the code. - Used template string interpolation (
${x}) instead of string concatenation for cleaner syntax. - Added detailed error logging to help debug any future issues with the AJAX request.
内容的提问来源于stack exchange,提问作者James Green

