为什么我的AJAX调用前缀web主机的url

Why does my AJAX call prefix the web host to the url?

本文关键字:主机 url web 前缀 我的 AJAX 调用 为什么      更新时间:2023-09-26

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

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服务获得正确的响应。我得到相同的问题在高页,除了它是前缀与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前面加上当前的网站地址?

在API URL前加上当前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);
        }
    });
}

有关相对url和绝对url的更多信息,请参阅印第安纳大学的教程

使用HTTP或HTTPS,否则将被视为本地资源。例子:

url: "http://api.openweathermap.org/data/2.5/weather?",

提供/ in path。如下-

   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);
            }
        });