XMLHttpRequest函数执行后控制台返回undefined问题求助
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.contentTypedoesn't exist: There's no built-incontentTypeproperty on the XHR object. You need to usexhr.getResponseHeader("Content-Type")to check the response type.- Overly strict Content-Type check: The actual
Content-Typeheader might include a charset (likeapplication/json; charset=utf-8), so checking for an exact match with"json"will fail. Useincludes()or a regex to check if it containsapplication/json. - Premature error logging: Your
elseclause triggers whenever the request isn't fully successful (even while the request is still in progress, whenreadyStateisn'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 whenreadyState === 4(request completed).
内容的提问来源于stack exchange,提问作者Gabriel Matei

