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 callsend()
. You're doing an asynchronous request, because you specified the third parameter for
open()
to betrue
. This means that by the time you request thereadyState
, 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.
精彩评论