2015-08-22 86 views
0

我得到以下在我的控制檯爲什麼我的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調用前面加上當前網站地址的網址?

+2

只需以'http://'開頭。更長的解釋作爲答案! –

回答

3

,它把當前URL到API的網址是因爲您提供的網址不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 VS絕對URL的更多信息,請訪問this tutorial from Indiana University

+0

那麼,那些是一些簡單的點!胡說 – Dominofoe

0

在路徑中提供/。如下所示 -

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

使用HTTP或HTTPS,否則將視爲本地資源。例如:

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