raja R
raja R

Reputation: 1

How to read xml file using JS

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?

Upvotes: 0

Views: 1062

Answers (2)

Sébastien RoccaSerra
Sébastien RoccaSerra

Reputation: 17201

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!

Upvotes: 0

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

Upvotes: 1

Related Questions