我在控制台中看到以下内容
GET http://localhost/FCC%20Projects/Show%20Local%20Weather/api.openweathermap.o…9999&lat=43.3104064&APPID=4c45bb0e6071b74cf43da0d4aa498377&_=1440245698059 404 (Not Found)
如果我取出 http://localhost/FCC%20Projects/Show%20Local%20Weather/
部分并将剩余部分粘贴到浏览器栏中,我会从 api 服务获得正确的响应。
我在 gh-pages 上遇到了同样的问题,只不过它以 GitHub 地址为前缀。 http://adoyle2014.github.io/FCC-ShowLocalWeather/
function apiCall(lat, long) {
$.ajax({
url: "api.openweathermap.org/data/2.5/weather?",
jsonp: "jsonp",
dataType: "jsonp",
data: {
lon: long,
lat: lat,
APPID: apiKey
},
success: function (response) {
parseWeather(response);
}
});
为什么此 API 调用会在 url 前面添加当前网站地址?
最佳答案
它将当前 URL 附加到 API URL 之前的原因是您提供的 URL 不是以 http://
开头,这意味着它是一个相对 URI。他们认为这个 URI 是相对于当前 URL 的,因此他们将当前 URL 添加到它的前面,然后从那里开始。
要解决此问题,只需以 http://
开头 URI:
function apiCall(lat, long) {
$.ajax({
//This is our fix:
url: "http://api.openweathermap.org/data/2.5/weather?",
jsonp: "jsonp",
dataType: "jsonp",
data: {
lon: long,
lat: lat,
APPID: apiKey
},
success: function (response) {
parseWeather(response);
}
});
}
有关相对 URI 与绝对 URL 的更多信息,请访问 this tutorial from Indiana University .
关于javascript - 为什么我的 AJAX 调用会将 Web 主机作为 URL 前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32156128/