2

I have found the following piece of code which uses XmlHttpRequest to read JSON data from another domain. It works without using JSONP. I thought it is not possible (http://en.wikipedia.org/wiki/Same_origin_policy) . Why does it work?

    <script type="text/javascript">
      // Set up the http request object for AJAX calls
      var http = false;
      if(navigator.appName == "Microsoft Internet Explorer") http = new ActiveXObject("Microsoft.XMLHTTP");
      else http = new XMLHttpRequest();

      // Begin by getting partial codelist for all regions in the United Kingdom from the API in JSON format
      http.open("GET", "http://www.nomisweb.co.uk/api/v01/dataset/nm_1_1/geography/2092957697TYPE480.def.sdmx.json", true);
      http.onreadystatechange=function() {
        if(http.readyState == 4 && http.status == 200) {
          // Evaluate the JSON response
          var jsonlist = eval("(" + http.responseText + ")");

          // String to hold the html for area selection buttons
          var mycodelist = '';

          // Loop through each code in the codelist and build up buttons for the user to click
          for(i = 0; i < jsonlist.structure.codelists.codelist[0].code.length; i++)
          {
             // Get the code value
             var code = jsonlist.structure.codelists.codelist[0].code[i].value;

             // Get the description value
             var desc = jsonlist.structure.codelists.codelist[0].code[i].description.value;

             // Construct the html for this area button
             mycodelist += '<input type="button" onclick="getdata(' + code + ',\'' + desc + '\');" value="' + desc + '"><br>';
          }

          // Display the area selections in the "mylist" div
          document.getElementById('mylist').innerHTML = mycodelist;
        }
      }
      http.send(null); // Make the API request

    </script>

It works in Chrome.

http://www2.esd.org.uk/betaesdmapping/1234.HTML

UPDATE

It does not work in FF 3.6 or IE 7.

Maxim

Maxim Eliseev
  • 3,248
  • 4
  • 29
  • 35

1 Answers1

0

It is possible to circumvent the Same Origin Policy. Have a look at this wiki.

This is probably Cross-Origin Resource Sharing.

Basically, the server that hosts the file that is being requested by AJAX has specified that the requesting page is allowed access to that particular resource. In Apache this is done with the following line in the config file:

Access-Control-Allow-Origin: http://www.example.com

Community
  • 1
  • 1
Jivings
  • 22,834
  • 6
  • 60
  • 101