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

XMLHttpRequest函数执行后控制台返回undefined问题求助

Fixing Your myRequest Function's Undefined Return & Other Issues

Hey there, let's walk through why your myRequest function is returning undefined and iron out the bugs in your code:

1. The Root Cause of undefined Return

Your function uses asynchronous XMLHttpRequest—when you call xhr.send(), the browser kicks off the request in the background, and the function immediately finishes executing (without waiting for the response). Since there's no explicit return statement in your function, it defaults to returning undefined.

Async operations need a way to pass back results once they're ready—we can use Promises (modern approach) or callbacks for this.

2. Bug Fixes in Your Existing Code

You've got a couple of issues in your onreadystatechange handler:

  • xhr.contentType doesn't exist: There's no built-in contentType property on the XHR object. You need to use xhr.getResponseHeader("Content-Type") to check the response type.
  • Overly strict Content-Type check: The actual Content-Type header might include a charset (like application/json; charset=utf-8), so checking for an exact match with "json" will fail. Use includes() or a regex to check if it contains application/json.
  • Premature error logging: Your else clause triggers whenever the request isn't fully successful (even while the request is still in progress, when readyState isn't 4). This will log "This is not a Json file" multiple times before the request completes, which is misleading.

3. Fixed Version Using Promises

Here's a cleaned-up, modern version of your function that returns a Promise so you can handle the response properly:

function myRequest(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          const contentType = xhr.getResponseHeader("Content-Type");
          // Check if response is JSON (account for possible charset)
          if (contentType && contentType.includes("application/json")) {
            console.log("Type", contentType);
            console.log("Text", xhr.responseText);
            resolve(xhr.responseText); // Resolve with the JSON text
          } else {
            const error = new Error("Response is not a JSON file");
            console.log(error.message);
            reject(error);
          }
        } else {
          const error = new Error(`Request failed with status ${xhr.status}`);
          console.log(error.message);
          reject(error);
        }
      }
    };
    
    xhr.onerror = function() {
      const error = new Error("Network error occurred");
      console.log(error.message);
      reject(error);
    };
    
    xhr.send();
  });
}

How to Use It:

// Call the function and handle the result
myRequest("your-url-here")
  .then(response => {
    // Do something with the JSON response
    const data = JSON.parse(response);
    console.log("Parsed JSON:", data);
  })
  .catch(error => {
    // Handle errors
    console.error("Request error:", error);
  });

4. Key Takeaways

  • Async functions can't return results directly—use Promises or callbacks to pass data once the operation finishes.
  • Always validate XHR properties correctly (don't use non-existent properties like xhr.contentType).
  • Be careful with conditional logic in onreadystatechange—only act when readyState === 4 (request completed).

内容的提问来源于stack exchange,提问作者Gabriel Matei

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:51:54