javascript – How can I make XHR.onreadystatechange return its result?

javascript – How can I make XHR.onreadystatechange return its result?

You are dealing with an asynchronous function call here. Results are handled when they arrive, not when the function finishes running.

Thats what callback functions are for. They are invoked when a result is available.

function get(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open(GET, url, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            // defensive check
            if (typeof callback === function) {
                // apply() sets the meaning of this in the callback
                callback.apply(xhr);
            }
        }
    };
    xhr.send();
}
// ----------------------------------------------------------------------------


var param = http://example.com/;                  /* do NOT use escape() */
var finalUrl = http://RESTfulAPI/info.json?url= + encodeURIComponent(param);

// get() completes immediately...
get(finalUrl,
    // ...however, this callback is invoked AFTER the response arrives
    function () {
        // this is the XHR object here!
        var resp  = JSON.parse(this.responseText);

        // now do something with resp
        alert(resp);
    }
);

Notes:

  • escape() has been deprecated since forever. Don not use it, it does not work correctly. Use encodeURIComponent().
  • You could make the send() call synchronous, by setting the async parameter of open() to false. This would result in your UI freezing while the request runs, and you dont want that.
  • There are many libraries that have been designed to make Ajax requests easy and versatile. I suggest using one of them.

You cant do it at all for asynchronous XHR calls. You cannot make JavaScript wait for the HTTP response from the server; all you can do is hand the runtime system a function to call (your handler), and it will call it. However, that call will come a long time after the code that set up the XHR has finished.

All is not lost, however, as that handler function can do anything. Whatever it is that you wanted to do with a return value you can do inside the handler (or from other functions called from inside the handler).

Thus in your example, youd change things like this:

    xhr.onreadystatechange = function()
    {
        if (xhr.readyState == 4)
        {
            var resp = JSON.parse(xhr.responseText);
            //
            // ... whatever you need to do with resp ...
            //
        }
    }
}

javascript – How can I make XHR.onreadystatechange return its result?

For small edit talking about post: https://stackoverflow.com/a/5362513/4766489

...
if (typeof callback == function) {
     //var resp  = xhr.responseText;
     var resp  = JSON.parse(xhr.responseText);
     callback(resp);
}
...

And when you call

...
function(data) {
    alert(data);
    /* now do something with resp */
}
...

Leave a Reply

Your email address will not be published.