Search code examples
javascriptsame-origin-policy

Is it possible to load and parse file on remote server?


Is it possible to download and parse a plain text file from different domain with JavaScript?

I've got this fiddle so far, but I'm stuck figuring out what I'm doing wrong.

Markup:

  <div id="clickme">Click me</div>
  <div id="result">Result: </div>

Code:

$("#clickme").click(function() {
  /* ###################################
     NOTE: im on say example.com/test.html but trying
     NOTE: to access different_domain_sample.com
   */
  var req = new XMLHttpRequest();
  var sURL = "http://www.google.com/robots.txt";

  req.open("GET", sURL, true);
  req.setRequestHeader("User-Agent", "blah/4.2");

  req.onreadystatechange = function() {
    if (req.readyState == 4) {
        $("#result").text("Result is: <pre>" + req.responseText + "</pre>");
    }
  };
  req.send(null);
});

Already answered, but more info on this is here Cross-origin resource sharing


Solution

  • There are three ways to do this:

    1. With the help of a non-browser-based proxy served from your domain which will fetch the data on your behalf. You can also use a plugin which can bypass the same-origin policy.
    2. Use JSONP or another similarly hackish way around the same-origin policy. This would require the web server to support JSONP.
    3. Disable the cross-origin policy (definitely not recommended; very dangerous)