页面加载时自动将URL响应数据渲染至HTML表格的技术问询
Fix: Load Data into Table on Page Load
Hey there! Let's get your script working so it populates the table as soon as the page finishes loading. Your core logic for fetching data and building the table is solid—you just have some syntax issues with how you're attaching the code to window.onload, plus a few extra bits that aren't needed.
What Was Wrong
- The
window.onloadassignment had incorrect syntax: you tried to wrap the AJAX call directly inside the function declaration without proper curly braces, and there were extra closing parentheses at the end. - The
return false;line was unnecessary here—you're not handling a form submission, so there's nothing to suppress.
Corrected Script
window.onload = function() { $.ajax({ type: 'GET', url: 'http://localhost:8080/imp/', dataType: "json", success: function(data) { if (data && data.length > 0) { let txt = ""; for (let i = 0; i < data.length; i++) { // Only add rows if both name and age exist if (data[i].name && data[i].age) { txt += `<tr><td>${data[i].name}</td><td>${data[i].age}</td></tr>`; } } if (txt) { $("#impExtTableID").append(txt).removeClass("hidden"); } } }, error: function(jqXHR, textStatus, errorThrown) { alert(`Error: ${textStatus} - ${errorThrown}`); } }); };
Key Improvements
- Proper
window.onloadwrapping: We correctly assign an anonymous function towindow.onload, which runs the AJAX call once the page is fully loaded. - Cleaned up conditionals: Combined the checks for
dataanddata.length > 0to simplify the code. - Template literals: Swapped out string concatenation with template literals (
${}) for more readable row building. - Removed unnecessary code: Got rid of the misplaced
return false;and extra closing brackets that were causing syntax errors.
This script will now automatically fetch your data and populate the table as soon as the page finishes loading, no click event required!
内容的提问来源于stack exchange,提问作者Parkavi
相关产品推荐
相关产品推荐

