简体   繁体   中英

NS_ERROR_FAILURE with JS XMLHttpRequest

I'm trying to load the source of a web page, as shown in "Javascript:The Definitive Guide" p.481, using firefox.

Here's my code:

  var request = new XMLHttpRequest();

  request.open("GET", "http://finance.yahoo.com/q?s=PG", false);

  request.send(null);

  if (request.status==200)  { alert(request.responseText);  }

  else {alert("Error "+request.status + ": "+request.statusText);} 

  </script>  

Firebug shows the GET statement, followed by 200 OK X 338ms.

Which looks like it was successful (code 200).

But the next Firebug line says: NS_ERROR_FAILURE, request.send(null);, with no further explanation.

and neither alert gets executed.

It doesn't help if I use help mode, and doesn't run in Chrome either. I don't have a popup or cookie or ad blocker running.

The page loads fine in perl with an LWP get().

If this is an inevitable cross-domain taboo, why doesn't the "definitive guide" say so?

I understand that JSONP returns JSON. I don't want that - I want just a string with the raw source, like with the perl LWP get().

Is this impossible with Javascript?

I suppose I could write a batch file which uses perl to get the source and put it into a JSON file whose name is hard-coded into the JS. But I'd like to avoid that sort of kludge.

In case it helps, I have run into this problem a couple times before, and ran into it again. If the answer to this question doesn't help you, try adding the following lines which helped me:

request.overrideMimeType('text/xml; charset=UTF-8'); // needed to get utf8 req's to work

or this debug line (which you can monitor on the web console of your browser)

request.onreadystatechange = function() {console.log("statechanged. url= " + url);};

before your

request.open()

where url is a var that holds the url you are trying to request. Sometimes it will give you that cryptic error if there is a problem getting the url, in my (last) case, it was because the url was malformed. Hope that helps someone out there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM