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

将原生JavaScript Ajax代码转换为jQuery时遇错误,求解决方案

Let's break down your issues one by one and fix the jQuery conversion step by step:

Key Issues & Fixes

  1. displayOutput is not defined Error
    The problem is you're using a const arrow function for displayOutput, 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 displayOutput definition inside the ready function, or use a function declaration (function displayOutput() {}) which gets hoisted.
  2. Cannot read property 'forEach' of undefined
    When you set dataType: 'JSON' in jQuery's AJAX, jQuery automatically parses the server response into a JavaScript object/array. Your code incorrectly tries to access response.responseText (this is a property of the raw XMLHttpRequest object, not jQuery's processed response). This makes data undefined, so calling forEach on it fails.

    • Fix: Use the response parameter directly as your parsed data.
  3. 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.
  4. Uncaught ReferenceError: data is not defined
    The console.log(data) outside the ready block is trying to access a variable that only exists inside the AJAX success callback (it's scoped locally there).

    • Fix: Move the console.log inside the success callback, or remove it.

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 newReleases and comingSoon variables 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:29:08