jQuery $.ajax run as a local HTML file avoiding SOP (same origin policy)

David picture David · Feb 3, 2013 · Viewed 7.8k times · Source

I created an HTML file foo.html with the following contents:

  <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script> 
      $.ajax({url:"http://foo.com/mdata",
        error: function (results) {
          alert("fail");
        },
        success: function (result) {
          alert("sucesses");
        }
      });
    </script>

When I load this HTML file in the web browser it always shows a dialog box with fail.

  1. Any idea why this is happening?
  2. Also what is the best way to debug this?

PS:

Assume that http://foo.com/mdata is a valid web service path.

EDIT#1

Solution

a similar code worked perfectly fine with me using $.getJson http://jsfiddle.net/dpant/EK3W8/

i also did save the content as a .html file and a request from file:// to an web service also seems to work.

<!DOCTYPE html>
<html>
<head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div id="images">

</div>
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  },
  function(data) {
    $.each(data.items, function(i,item){
      $("<img/>").attr("src", item.media.m).appendTo("#images");
      if ( i == 3 ) return false;
    });
  });</script>

</body>
</html>

Looks like most of the browsers supports the CROS so you can write a script save it as .html and open it in browser and it will do a Ajax request successfully *provided that the server you are making request supports it *. In this case my web server (service) does not support CROS (and default configuration of Apache will not support it).

Many of the web-services have enabled the CROS eg http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=? hence the request goes through successfully.

Few links:

http://enable-cors.org/

https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing

Answer

napolux picture napolux · Feb 3, 2013

It always fails for two reasons:

  • You need a webserver that answers to your request (200 = success, 404 i.e. is an error) on Linux you can easily setup one, on Windows and Mac look at Bitnami
  • You can't call a different domain via AJAX. If you're running your script on www.example.com you can't ask for www.example.net Look at the same origin policy.