Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

How to return a response from xmlhttprequest javascript

I don't know why this function is returning undefined. Please help me... Run Snippet

function xhr(url) {
    const xhr = new XMLHttpRequest();

    xhr.responseType = 'json';
    
    xhr.addEventListener("readystatechange", function () {
        if (this.readyState === this.DONE) {
            return (this.response);
        }
    });
    
    xhr.open("GET", url);
    xhr.send();

}

let arr =  xhr('https://reqres.in/api/users?page=2');
console.log(arr);
question from:https://stackoverflow.com/questions/65931174/how-to-return-a-response-from-xmlhttprequest-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is very very simple, Maybe you're new to Javascript, If you are not aware Js is an asynchronous language, it means that it would not block or wait for any function to complete which might be time consuming ( in this case a request to the server), This helps it to process other things meanwhile the request is taking place.

So in your case, it's creating the request to the server, but at the same time continues to execute your function and return the default value, i.e undefined, You can pass a callback to be called when the request is completed.

function callWhenFinished(arr) {
  console.log(arr);
}


function xhr(url) {
  const xhr = new XMLHttpRequest();

  xhr.responseType = 'json';

  xhr.addEventListener("readystatechange", function() {
    if (this.readyState === this.DONE) {
      callWhenFinished(this.response); // callback
    }
  });

  xhr.open("GET", url);
  xhr.send();

}


xhr('https://reqres.in/api/users?page=2');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...