XmlHttpRequest - 可以从其他域读取JSON吗?

时间:2012-02-09 12:55:18

标签: ajax json

我找到了以下代码,它使用XmlHttpRequest从另一个域读取JSON数据。它不使用JSONP就可以工作。我认为这是不可能的(http://en.wikipedia.org/wiki/Same_origin_policy)。它为什么有效?

    <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>

适用于Chrome。

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

更新

它在FF 3.6或IE 7中不起作用。

Maxim

1 个答案:

答案 0 :(得分:0)

可以绕过同源政策。看看this wiki

这可能是Cross-Origin Resource Sharing

基本上,承载AJAX请求的文件的服务器已指定允许请求页面访问该特定资源。 在Apache中,这是通过配置文件中的以下行完成的:

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