XMLHttpRequest异步请求返回undefined问题求助
perso Variable in Your Async XHR Request Hey there! No worries about the English—let's get this sorted out together 😊
You're absolutely right about the root cause: your uhttp function uses an asynchronous XMLHttpRequest, which means the function finishes executing before the server sends back a response. That's why perso ends up as undefined when you try to use it.
Here's how to fix it step by step:
1. Rewrite uhttp to return a Promise
Promises are perfect for handling asynchronous operations—they let us "wait" for the response before moving on. Let's refactor your function:
function uhttp(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('get', url, true); xhr.responseType = 'json'; xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.response); resolve(xhr.response); // Pass the successful response to the Promise } else { reject(new Error(`Request failed with status: ${xhr.status}`)); // Handle errors } }; xhr.onerror = function() { reject(new Error('Network error occurred while fetching data')); }; xhr.send(); }); }
2. Use async/await to wait for the response
Since we're returning a Promise, we can use await in an async function to pause execution until the request finishes. We'll also fix a couple of typos in your code:
(async () => { try { const perso = await uhttp('bd.php?table=charac'); // Fixed typos: `lenght` → `length`, `getElementbyID` → `getElementById` for (let i = 0; i < perso.length; i++) { // A cleaner, safer way to add elements (instead of string concatenation) const ulElement = document.createElement('ul'); ulElement.textContent = perso[i].nom; document.getElementById('container').appendChild(ulElement); // If you prefer string syntax, use innerHTML (but be cautious with user input): // document.getElementById('container').innerHTML += `<ul>${perso[i].nom}</ul>`; } } catch (error) { console.error('Oops, something went wrong:', error); } })();
Quick notes on the typos:
lenghtis a common misspelling—correct islengthgetElementbyIDneeds capitalizedBandD:getElementById
This approach ensures your code waits for the API response before trying to loop through the perso data, so you won't get undefined anymore.
内容的提问来源于stack exchange,提问作者Antoine Guil

