我有从外部网站加载的JSON脚本。在最简单的形式,在code一直是这样(和工作):
I have a JSON script loaded from an external website. In its simplest form, the code has been like this (and working):
jQuery.getJSON("http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?",
function(data){
document.querySelector("output").textContent = data.postal_codes[0].city;
});
不过,网站所有者不希望jQuery的,如果它不是关键的,所以我重新codeD .getJSON
到请求=新XMLHtt prequest();
型号:
request = new XMLHttpRequest();
request.open("GET", "http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?", true);
request.onload = function() {
var data = JSON.parse(request.responseText);
document.querySelector("output").textContent = data.postal_codes[0].city;
};
request.onerror = function() { /* this gets called every time */ };
我修改我的code很多次,再读单证遍地,然而 .onerror
函数是唯一一个始终显示。这是控制台:
I've modified my code many times, read documentations over and over again, yet the .onerror
function is the only one always displaying. This is the console:
这在挪威的说,这个剧本要求CORS,它无法找到访问控制 - 允许 - 原产地的负责人的起源,那XMLHtt prequest了网络错误,并说不访问。
Which in Norwegian says that this script requested CORS, that it can't find the origin in the head of Access-Control-Allow-Origin, and that the XMLHttpRequest had a network error, and says "no access".
这可能有几个原因,为什么出现这种情况:
There could be several reasons as to why this occurs:
1 有什么毛病了新的code
1: There's something wrong with the new code
2 有什么东西在 .getJSON
jQuery函数(?黑客攻击)是$ P $的发生pvents错误
2: There's something in the .getJSON
jQuery function (a hack?) that prevents the error from happening
3 有什么东西在新的code,我已经忘了添加关键
3: There's something crucial in the new code that I have forgot adding
4:有一些与我的浏览器(IE 11的那一刻)
4: There's something with my browser (IE 11 at the moment)
5:别的东西
这将是可爱的有一些这方面的帮助。
It would be lovely with some help on this.
演示: http://jsbin.com/muxigulegi/1/
这是不是网络错误。这是一个跨起源错误。该请求是成功的,但在浏览器拒绝访问响应你的JavaScript。
That isn't a network error. It's a cross origin error. The request is successful but the browser is denying access to the response to your JavaScript.
既然你有回调=?
的URL,jQuery将产生一个JSONP请求,而不是一个XMLHtt prequest请求。这执行响应作为脚本而不是读的原始数据。
Since you have callback=?
in the URL, jQuery will generate a JSONP request instead of an XMLHttpRequest request. This executes the response as a script instead of reading the raw data.
您手动创建一个XMLHtt prequest,所以失败是由于同源策略。
You are manually creating an XMLHttpRequest, so it fails due to the Same Origin Policy.
Create一个JSONP请求代替。