javascript - 为什么我的 AJAX 调用会将 Web 主机作为 URL 前缀?

标签 javascript jquery ajax

我在控制台中看到以下内容

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/

相关文章:

javascript - $watch 不工作

javascript - 下载google suggest javascript文件的链接是什么?

javascript - 当我在 Three.js 中使用加载器时,变量未定义

javascript - 如何从数组中提取特定的一段json

javascript - 使用 jQuery 克隆 div 并增加子类

jquery - 如何在文档加载时立即进行 AJAX 调用

javascript - 重力点不能与其他元素一起正常工作

jquery - 如何使用 jQUery Ajax 更新表行?

javascript - jQuery Ajax-load 替换 IE9 中的页面而不是 div(无需开发人员工具模式切换)

javascript - 无法使用javascript获取数组中当前单击元素的索引