json数组可通过浏览器获得,但通过getJSON无声地失败

时间:2016-12-19 12:33:18

标签: javascript json web-services getjson

这是我第一次来这里,请耐心等待。

我有两个类似的web apis,都可以使用浏览器访问,但只有一个可以使用jquery。是什么给了什么?

这个可以使用浏览器并使用getjson,所有这些都很好:

$.getJSON( "http://api.openweathermap.org/data/2.5/weather?q=london&appid=33d0ba5efa0edb1a2282c3165b00d15e&units=metric")
.done(function( json ) {
console.log( "JSON Data: " + json.name );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});

下面的这个几乎是相同的,但只有你去地址才可用,如果你试图让json无声地失败或抛出错误:

$.getJSON( "http://info.studyinpoland.pl/admin/public/api/events")
.done(function( json ) {
console.log( "JSON Data: " + json[0].id );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});

为什么这会失败?我需要来自http://info.studyinpoland.pl/admin/public/api/events的数据,我还可以使用javascript访问它吗?

2 个答案:

答案 0 :(得分:0)

如果您查看控制台,则会收到此错误" XMLHttpRequest无法加载http://info.studyinpoland.pl/admin/public/api/events?_=1482151092048。 No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' http://stackoverflow.com'因此不允许访问。"

要解决这个问题,我所做的就是从我的后端而不是前端调用我的ajax调用,它的工作正常。

希望这会有所帮助:)

答案 1 :(得分:-2)