2013-02-18 53 views
0

我想從以下API URL拉一個簡單的「當前天氣」狀態,融入到一個網站:拉動簡單天氣變量(JSON/API)

http://free.worldweatheronline.com/feed/weather.ashx?q=67554&format=json&num_of_days=2&key=794496e1c2020558131802

我在尋找一個解決問題的兩種解決方案。無論是爲什麼這段代碼都不會返回一個簡單的「測試」,一些洞察力。 (如果我刪除了「$ .getJSON」行)。或者我需要包含current_conditions> temp_F的完整jQuery。

<script> 
    $(document).ready(function(){ 
     $.getJSON(
       'http://free.worldweatheronline.com/feed/weather.ashx?q=67554&format=json&num_of_days=2&key=794496e1c2020558131802', 
       function(data) { 
        var output="Testing."; 
        document.getElementById("weather").innerHTML=output; 
       }); 
    }); 
</script> 

感謝您的幫助提前;對此,我真的非常感激!

回答

3

這是因爲Same Origin Policy。您應該使用jsonp &你的代碼改成這樣:

$(document).ready(function() { 
    $.ajax({ 
     url: 'http://free.worldweatheronline.com/feed/weather.ashx?q=67554&format=json&num_of_days=2&key=794496e1c2020558131802', 
     type: "GET", 
     dataType: "jsonp", 
     success: function (data) { 
      console.log(data); //to see that data is indeed returned 
      var output = "Testing."; 
      $("#weather").html(output); 
     } 
    }); 
}); 
+1

是的,我剛剛輸入了這同樣的事情,但你首先回答。這裏是[小提琴](http://jsfiddle.net/4KN69/)我把它放進去。 – 2013-02-18 04:24:01

+0

完美,非常感謝!只有我編輯(以防其他人在將來引用此問題)是因爲我們需要在「天氣」前面加一個'#',因爲它正在識別一個ID。 除此之外,真棒。 =)再次感謝! – cdwyer 2013-02-18 06:27:29

+0

@cdwyer謝謝你指出,回答編輯。 – 2013-02-18 06:43:30