开发者

Issue with xmlHttp.send() method

I am trying to lo开发者_运维技巧ad an XML file and get its DOM object. I think the error is with this code:

// Takes an XML document and loads it and returns a DOM of the document
function loadXMLDoc(filepath)
{
    if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
    {
        xmlhttp = new XMLHttpRequest();
    }
    else // code for IE6, IE5
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", filepath, false);
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML;
    return xmlDoc;
}

The code stops executing at xmlhttp.send(). I get the following error message:

XMLHttpRequest cannot load file://localhost/Users/Dylan/programming/projects/personalpage/resources/cool-data.xml. Cross origin requests are only supported for HTTP.
Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101

This highlights the xmlhttp.send() line. I had this working before and I don't think I made any changes to the file. The only difference I know is that I am now executing this on my local machine. Before I was using an IDE hosted online (cloud9) so the files were all remote on a web server. Also, it worked on Windows and I'm now on a Mac.

Edit: I called the function with the argument: "../resources/items-data.xml" and all of my work is on my local machine. Equal level directories are js, html, css, and resources.


You could use XHR locally (in file: origin), but there is a catch: Google Chrome and Firefox (I believe) will prevent you from accessing files other than the files in the same directory with the html file. That is

file://localhost/Users/Dylan/programming/projects/personalpage/index.htm

can access

file://localhost/Users/Dylan/programming/projects/personalpage/abc.xml, or file://localhost/Users/Dylan/programming/projects/personalpage/abc.json.js

but not

file://localhost/Users/Dylan/programming/projects/personalpage/resources/cool-data.xml, or file://localhost/etc/passwd

This restriction has only be added to recent version. I guess that's the reason you didn't find out in the first place.

P.S. Next time, do everybody a favor by using jQuery or other Javascript library rather than reinventing the wheel.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜