0

I am using the following code to read the xml file from JS

function ReadFile(xmlPath) {

  oxmlhttp = null;

  try {
    // Firefox, Chrome, etc... Browsers
    oxmlhttp = new XMLHttpRequest();
    oxmlhttp.overrideMimeType("text/xml");
  } catch (e) {

    try {
        // IE Browser
        oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        return null;
    }
  }

  if (!oxmlhttp) return null;

  try {
     oxmlhttp.open("GET", xmlPath, false);
     oxmlhttp.send(null);
  } catch (e) {
     return null;
  }

  var xmlDoc = oxmlhttp.responseXML.documentElement;
  alert(xmlDoc);
  return oxmlhttp.responseText;

}

It's working fine for IE and Firefox but not in Chrome. the following exception "XMLHttpRequest cannot load the file. Cross origin requests are only supported for HTTP." should occur when i use chrome.

Can anybody know how to read the xml file in chrome using JS?

2 Answers 2

1

According to the error, there is some problem with the request domain. You shold alert the domain address of the request:

...
try {
   alert(xmlPath) //alerting
   oxmlhttp.open("GET", xmlPath, false);
   oxmlhttp.send(null);
} catch (e) {
   return null;
}
...

and the xmlPath sould not contain and another domain address. read this issue aboute this: Cross domain Ajax request from within js file

Sign up to request clarification or add additional context in comments.

3 Comments

I am curious that Firefox and IE load the XML correctly where they shouldn't. Don't they block cross-origin XHR?
they do. the problem would be some browser specific probblem. you shoudl alert your code and see what is it, and change if not correct.
Thanks for your response. Ya, i tried it, actually i am reading a xml file from local machine memory.
0

Are you serving the xml file, or are you making tests using your file system ?

If you're using the file system, I'd recommend starting a small HTTP server on your site dir instead.

You can easily start a HTTP server to serve a directory, e.g. serve the current directory with Python:

$ python -m SimpleHTTPServer

Or if you're using Windows, maybe you'll like HFS better for the same purpose: http://www.rejetto.com/hfs/

Cheers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.