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

XMLHttpRequest异步请求返回undefined问题求助

Fixing the 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:

  • lenght is a common misspelling—correct is length
  • getElementbyID needs capitalized B and D: 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:51:19