2012-10-18 21 views
1

我使用下面的代碼從這個JSON獲取一些元素,但似乎沒有任何工作。任何人都知道我做錯了什麼? (我花了很長時間試圖弄清楚)。從json獲取元素到html與jQuery不工作

$(document).ready(function() { 

$.getJSON('http://free.worldweatheronline.com/feed/weather.ashx?q=Stockholm&format=json&num_of_days=2&key=e8536d3a52101433121710', function(Wdata) { 
       $.each(Wdata.data, function() { 

       $('<div id="test"></div>').append(

         this.weather[0].date; 

         ).appendTo('body'); 

        }); 
    }); 
}); 

我的HTML看起來像這樣:

<!doctype html> 
<html lang="se"> 
    <head> 
     <meta charset="utf-8" /> 
     <title>Title of This Web Page</title> 
     <script src="scripts\jquery-1.8.2.js" type="text/javascript"></script> 
     <script src="scripts\js.js" type="text/javascript"></script> 
    </head> 

    <body> 
       <div id="test"> 
       </div> 
    </body> 

</html> 

的JSON看起來是這樣的:

{ 

    "data": { 
     "current_condition": [ … ], 
     "request": [ … ], 
     "weather": [ 
      { 
       "date": "2012-10-17", 
       "precipMM": "0.8", 
       "tempMaxC": "11", 
       "tempMaxF": "51", 
       "tempMinC": "8", 
       "tempMinF": "46", 
       "weatherCode": "119", 
       "weatherDesc": [ 
        { 
         "value": "Cloudy" 
        } 
       ], 
       "weatherIconUrl": [ 
        { 
         "value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0003_white_cloud.png" 
        } 
       ], 
       "winddir16Point": "SW", 
       "winddirDegree": "224", 
       "winddirection": "SW", 
       "windspeedKmph": "27", 
       "windspeedMiles": "17" 
      }, 
      { … } 
     ] 
    } 

} 

回答

0

使用JavaScript控制檯。閱讀它給你的錯誤。

Uncaught SyntaxError: Unexpected token ;

終止語句,而不是表達式。取出;this.weather[0].date;

如果解決這個問題,那麼你得到:

XMLHttpRequest cannot load http://free.worldweatheronline.com/feed/weather.ashx?q=Stockholm&format=json&num_of_days=2&key=e8536d3a52101433121710. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.

這是well covered on this site

+0

我如何看到我所得到的?因爲我沒有看到任何東西...... – user1755603

+0

您在瀏覽器中打開JavaScript控制檯。在Chrome中,它位於工具>開發者工具下。 – Quentin

+0

感謝您的幫助! – user1755603

0

如果您的請求OS跨域=網址是不是從你的域名,你應該設置跨域標誌或使用jsonp代替。

+0

如何設置跨域標誌? – user1755603

+0

閱讀此: http://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working – CodeWizard

+0

這是一個小插件,將幫助你做它 https://github.com/padolsey/jQuery-Plugins/tree/master/cross-domain-ajax/ – CodeWizard