如何让XHR.onreadystatechange返回其结果? [英] How can I make XHR.onreadystatechange return its result?

查看:1707
本文介绍了如何让XHR.onreadystatechange返回其结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript编程的新手。我现在正在处理我的Google Chrome扩展程序。这是不起作用的代码......:P

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

我希望 getURLInfo 函数返回其JSON对象,并希望将其放入 resp 。有人可以修改我的代码以使其正常工作吗?

I want getURLInfo function to return its JSON object, and want to put it into resp. Could someone please fix my code to get it work?

function getURLInfo(url)
{
    var xhr = new XMLHttpRequest();
    xhr.open
        (
            "GET",
            "http://RESTfulAPI/info.json?url="
                + escape(url),
            true
        );
    xhr.send();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState == 4)
        {
            return JSON.parse(xhr.responseText);
        }
    }
}
var resp = getURLInfo("http://example.com/") // resp always returns undefined...

提前致谢。

推荐答案

您正在处理异步函数调用。结果在到达时处理,而不是在函数完成运行时处理。

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);
    }
);

注:


  • escape()已被永久弃用。不要使用它,它无法正常工作。使用 encodeURIComponent()

  • 可以制作 send()通过将 open() async 参数设置为假。这会导致您的UI在请求运行时冻结,并且您不希望这样。

  • 有许多库旨在使Ajax请求变得简单和通用。我建议使用其中一个。

  • 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.

这篇关于如何让XHR.onreadystatechange返回其结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆