Im using firefox 3.6.10, and firebug to debug
So, here is my code:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url,false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(null);
alert(xmlhttp.responseXML);
responseXML is always null, and i've tried it on several URLs from different domains. I have also tried it asynchronously, it's the same result. The responseText is always properly returned, no problems with it.
My goal is to get the responseXML.documentElement.
Thanks for your help.
EDIT-----------
This javascript code was executed from a Greasemonkey userscript, i made surte its the same origin as the requested url. Also i tried executing from firebug console, again ensuring the origin policy. Same error on both.
Gotta hate javascript.
Besides the cross-domain issues already mentioned, responseXML
requires completely valid XML and probably the correct Content-Type
in the response headers sent from the server. It is very unlikely that either of these requirements would be met by the average website.
For the latter issue, you can use
xmlhttp.overrideMimeType('application/xml');
before you send the request to force the response to be interperted as XML. Still if the response is not valid XML, you will only get null
.
If i recall correctly , this is a known problem with firefox ( i have had the same problem before ).
The fix is to parse the responseText back to an XML document , and then use this.
Something like this :
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlhttp.responseText, "application/xml");
I bet you are violating the same origin policy.
For XHRs, you must have the same protocol, domain, port, etc. So if you are running an app on localhost:8080/app, you CANNOT ajax to www.cnn.com.
Different browsers handle this differently; I have seen FF do what you describe, which is the request appears to return normally but there is no data...
Try to open the value of url
directly in the browser. You should get some error information.
If you see a parsing error, chances are your encoding is wrong and you have a special character in your XML that makes it invalid.
To avoid that, you need to be sure that all the chain is properly encoded.
If it is a static XML file, you need to set correctly your editor encoding when saving it. The encoding that does it all(almost) is UTF-8, it is usually a property you can choose in your editor settings or in the save dialog.
If it is dynamically generated. Your data, the page and the server response must be properly encoded too. And your XML starting with <?xml version="1.0" encoding="UTF-8"?>
You can try first with a very basic and static XML:
<?xml version="1.0" encoding="UTF-8"?><root>hi</root>
And then add the steps, one by one to make it like yours, without breaking it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With