开发者

nsIXMLHttpRequest executes only till readyState 1

I am using the following script to load some data through the firefox extension UI.

var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance();
var www = "http://localhost/view?url=http://google.com";
req.open('GET', www, true);

if (req.readyState){
    alert(req.readyState);
}

It alerts just 1.

The script shows no error in the error console with the strict java开发者_JS百科script being enabled.


There are two problems with your code:

  • You've forgotten to call req.send(null). The request will only execute when you call send().
  • You're doing an asynchronous request, because you specified the third parameter for open() to be true. This means that by the time you request the readyState, the request will still be executing. You should instead use a readystatechange listener as so:

    req.onreadystatechange = function (aEvt) {
        if (req.readyState == 4) {
            if(req.status == 200)
                dump(req.responseText);
            else
                dump("Error loading page\n");
        }
    };
    

I suggest taking a look at the documentation on Using XMLHttpRequest, which contains the example above and several others.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜