简体   繁体   English

JavaScript CORS JSON / JSONP请求

[英]Javascript CORS JSON/JSONP Request

I have browsed most CORS and JSON request topics, and cannot understand why this first script works, but not the second. 我浏览了大多数CORS和JSON请求主题,但无法理解为什么第一个脚本有效,而第二个脚本却无法正常工作。 I would love to be educated in the ways of CORS and Javascript and XMLHTTPRequest2 and AJAX. 我希望以CORS和Javascript以及XMLHTTPRequest2和AJAX的方式受教育。

This works: 这有效:

function wfs() {
 var url = 'http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles&callback=getRoute';
 var script = document.createElement('script');
 script.type="text/javascript";
 script.src=url;
 document.getElementsByTagName('head')[0].appendChild(script);
}

function getRoute(response) {
 console.log(response);
}

This does not work: 这不起作用:

function wfs() {
 var url = 'http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles';
 var xhr = new XMLHttpRequest();
 xhr.open('GET', url, true);
 xhr.onload = function(e) {
  if (this.status == 200) {
    var json = this.response;
    console.log(json);
  }
 };

 xhr.send();
}

Firebug shows a Red 200 Null Response. Firebug显示红色200 Null响应。

However, the second script does work when I use a different url: 但是,当我使用其他网址时,第二个脚本确实可以工作:

var url = 'http://ip.jsontest.com/?mime=2';

The first domain, http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles , does not implement CORS (ie does not send a usable Access-Control-Allow-Origin header). 第一个域http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles ,不实现CORS(即,不发送可用的Access-Control-Allow-Origin标头)。 http://ip.jsontest.com/?mime=2 does. http://ip.jsontest.com/?mime=2可以。 There is nothing you can do about this -- it depends on the server. 您对此无能为力-这取决于服务器。

The first block of code uses JSONP. 第一部分代码使用JSONP。 What this actually does is inject a script tag into the document. 这实际上是将脚本标签注入文档中。 Script tags can have external sources (if they are not of the same scheme, they may be blocked for security reasons). 脚本标签可以具有外部源(如果它们不是同一方案,则出于安全原因可能会被阻止)。 This allows the server to essentially send you javascript code that you insert into a <script> that gets run immediately. 这实际上允许服务器向您发送您插入到<script>中并立即运行的javascript代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM