开发者

Problem in Loading xml from specified url using javascript in FF & Google Chrome

I need to load xml file from specified url using javascript. Here is what i am doing:

function GetXMLDoc() {
    var url = 'http://www.warm.fm/exports/NowOnAir.xml';
    var httpRequest = null;
    try {
        httpRequest = new ActiveXObject('Msxml2.XMLHTTP'); 
    }
    catch (e) {
        try {
            httpRequest = new ActiveXObject('Microsoft.XMLHTTP'); 
        }
        catch (e2) {
            try {
                httpRequest = new XMLHttpRequest(); 
            }
            catch (e3) { httpRequest = false; }
        }
    }
    if (httpRequest) {
        httpRequest.open('POST', url, false);
        httpRequest.setRequestHeader("Content-Type", "text/xml");
 开发者_如何学C       httpRequest.send(null);
        alert(httpRequest.responseText);
    }
    else {
        alert(httpRequest);
    }

It works perfectly in IE but it does not in FF and Google Chrome. Firebug shows me the following error:

uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIXMLHttpRequest.send]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://localhost:49697/XMLParser.js :: GetXMLDoc :: line 43" data: no]

Is there anyone who has the answer that will help me in solving the issue?

Thanks, Mohin


    httpRequest.open('POST', url, false);
    httpRequest.setRequestHeader("Content-Type", "text/xml");
    httpRequest.send(null);

This doesn't really make sense. You're doing a POST and claiming that you're sending an XML file as the request body, but then sending nothing.

I suggest you really want to do a simple GET:

    httpRequest.open('GET', url, false);
    httpRequest.send();

Naturally you will have to do this from a document on www.warm.fm to satisfy the same origin policy; localhost won't work.

And I would seriously reconsider the synchronousness of the request (open...false). This is freeze the browser whilst the file is fetched, which is pretty user-hostile. Asynchronous requests with an onreadystatechange callback are almost always preferable.

Also, the cross-browser xmlhttprequest stuff is a bit old fashioned, and tries ActiveXObject first. Native XMLHttpRequest is usually the one to go for first. Try this IE6 fallback code instead:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    }
}

then you can just do new XMLHttpRequest() on any browser.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜