我试图让一个jQuery 阿贾克斯()
打电话公共Web服务,而且我无法找到正确的语法。
I'm trying to make a jQuery .ajax()
call to a public web service, and I'm having trouble finding the right syntax.
我已经尝试了几种不同的实现。这其中:
I've tried several different implementations. This one:
$.ajax({
url: 'http://www.geognos.com/api/en/countries/info/all.jsonp',
dataType: "jsonp",
success: function() {
alert('JSONP call succeeded!');
}
});
它失败,出现以下错误:
It fails with the following error:
all.jsonp:1 Uncaught ReferenceError: callback is not defined
和这一个:
$.ajax({
url: 'http://www.geognos.com/api/en/countries/info/all.json',
dataType: "json",
success: function() {
alert('JSON call succeeded!');
}
});
与此错误失败:
Fails with this error:
XMLHttpRequest cannot load http://www.geognos.com/api/en/countries/info/all.json. Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin.
我通过我的本地IIS7的情况下提供该页面。我也试过 $的各种组合。的getJSON()
类似的结果。我在想什么?
I'm serving the page through my local IIS7 instance. I've also tried various combinations of $.getJSON()
with similar results. What am I missing?
下面是上述code进行的jsfiddle 。
更新:认为我们有一个解决方案,但我仍然得到回调没有定义
错误时做JSONP调用,即使警报/日志code被调用。响应URL看起来是这样的:
UPDATE: Thought we had a solution, but I'm still getting the callback is not defined
error when doing the JSONP calls, even though the alert/log code gets called. The response URL looks like this:
http://www.geognos.com/api/en/countries/info/all.jsonp?callback=undefined&157148585
和JSON响应被包裹这样的:
and the JSON response is wrapped like this:
callback({"StatusMsg": "OK", "Results": {"BD": {"Name": "Bangladesh", "Capital": {"DLST": "null", "TD": 6.0, "Flg": 2, "Name": "Dhaka", ...
我发现有添加到URL的末尾,在阿贾克斯()
配置回调名字的例子,但是当我尝试,我得到了相同的因此,只有它上涨到我的查询字符串的结尾。
I've found examples with the callback name added on to the end of the URL in the .ajax()
configuration, but when I try that I get the same result, only it's tacked on to the end of my query string.
推荐答案
由于同源策略的这个正JSON调用将无法正常工作。这是你的错误是在告诉你:不受访问控制 - 允许 - 原产地允许
This regular JSON call will not work because of same origin policy. This is what your error is telling you with: is not allowed by Access-Control-Allow-Origin
.
正确的JSONP语法是:
$.ajax({
url: 'http://www.geognos.com/api/en/countries/info/all.jsonp',
dataType: "jsonp",
jsonpCallback: 'callback',
success: function(data) {
console.log(data);
}
});
DEMO
相关推荐
最新文章