How can I make XHR.onreadystatechange return its result?

后端 未结 3 2204
無奈伤痛
無奈伤痛 2020-12-14 03:16

I\'m new to JavaScript programming. I\'m now working on my Google Chrome Extension. This is the code that doesn\'t work... :P

I want getURLInfo function

相关标签:
3条回答
  • 2020-12-14 03:40

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

    That's 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 don't want that.
    • There are many libraries that have been designed to make Ajax requests easy and versatile. I suggest using one of them.
    0 讨论(0)
  • 2020-12-14 03:42

    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 */
    }
    ...
    
    0 讨论(0)
  • 2020-12-14 03:55

    You can't 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, you'd change things like this:

        xhr.onreadystatechange = function()
        {
            if (xhr.readyState == 4)
            {
                var resp = JSON.parse(xhr.responseText);
                //
                // ... whatever you need to do with "resp" ...
                //
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题