簡體   English   中英

使用$ .getjson從外部源請求JSON。 200成功但是在哪里呢?

[英]Request for JSON from externel source using $.getjson. 200 success but where is it?

我正在嘗試從openweathermap獲取天氣數據。 該網址適用於我輸入的坐標,在瀏覽器欄中輸入網址時,我可以下載JSON。 我正在嘗試在我的頁面中使用它。 當我運行此代碼時,在Firebug中,我可以看到HTTP請求獲得了200成功代碼,但是由於某種原因它沒有打印響應。 我沒有正確使用getJSON嗎?

var url = "http://api.openweathermap.org/data/2.5/forecast?lat="+ position.coords.latitude +"&lon=" + position.coords.longitude; 

$.getJSON(url, function(res) {
console.log(res);
});  

您正在嘗試在讀取JSONP的函數中讀取跨域JSON。 無法跨域JSON讀取。

嘗試JSONP請求;通過附加回調

    var url = "http://api.openweathermap.org/data/2.5/forecast?lat=" + 
position.coords.latitude +"&lon=" + position.coords.longitude + "&callback=?" ; 

    $.getJSON(url, function(res) {
    console.log(res);
    });  

JSON響應如下: { 'a':22 }

JSONP響應類似於: myFunction({'a':22} ) ,其中myFunction是作為callback傳遞的值

jQuery不需要回調函數的名稱,但是需要在URL中提及callback以便可以將其標識為JSONP請求。

JSONP

如果URL包含字符串“ callback =?” (或類似,由服務器端API定義),該請求將被視為JSONP。 有關更多詳細信息,請參見$ .ajax()中有關jsonp數據類型的討論。

追加此?callback=? 到網址,然后重試,例如:

$.getJSON(url + '?callback=?', function(res) {
    console.log(res);
});

嘗試這個

 function buildQuery() {
     var str = "http://api.openweathermap.org/data/2.5/forecast?lat=27.175009&lon=78.041849";
            return "select * from json where url ='" + str + "' ";
        }

        $.ajax({
            url: 'http://query.yahooapis.com/v1/public/yql',
            data: {
                q: buildQuery(),
                format: "json"
            },
            dataType: "jsonp",
            success: function (data) {
                alert(JSON.stringify(data));
            },
            error: function (data) {
                consol.log(data);
            }
      });

工作演示:

http://jsfiddle.net/HWuDk/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM