2
我已经发现了下面的代码段,它使用XMLHttpRequest来从另一个域读取JSON数据。它的工作原理没有使用JSONP。我认为这是不可能的(http://en.wikipedia.org/wiki/Same_origin_policy)。它为什么有效?的XmlHttpRequest - 可以从其他域读JSON?
<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
UPDATE
它不工作,在FF 3.6或IE 7
马克西姆
你能解释一下为什么我粘贴的代码工作: 在Apache中,这是在配置文件中的下面这行? – 2012-02-09 13:02:04
不无服务器配置:) – Jivings 2012-02-09 13:02:40
更新我对CORS的答案。 – Jivings 2012-02-09 13:05:05