2014-01-15 132 views
0

我正在使用wunderground API來練習我的JS,並且有一個關於如何解析他們在撥打電話時返回的JSON響應的問題。解析JSON服務器響應

我有一個簡單的函數,我正在調用URL並接收響應並將其發送到iframe。在iframe中,我看到了原始的JSON。我想知道的是如何解析JSON並在iframe中顯示解析的信息。 (或一個div如果更簡單)

我假設它是JSON.parse的一些變體,但我還沒有能夠得到它以我想要的方式工作。

另外我更喜歡避免jquery我想用普通的JS。

function conditions(){ 
    var zip = document.getElementById("zip").value; 
    var url = "http://api.wunderground.com/api/<API_KEY>/conditions/q/" + zip + ".json" 
    { 
    window.open(url,"frame"); 
    } 

更新:這是我現在擁有的。我知道我正在執行這個錯誤。我還遇到同樣的原產地問題,不得不繞過Chromes安全測試。任何建議表示讚賞。

function conditions() { 

GET_JSON = function(callback){ 
var c = document.getElementById("zip").value; 
var x = new String("http://api.wunderground.com/api/KEY/conditions/q/" + c + ".json" +"?callback=JSONCallback"); 
    var req = new XMLHttpRequest(); 
    req.open("GET", x, true); 
    req.onreadystatechange = function(){ 
     if(this.readyState==4){ 
      callback(JSON.parse(req.responseText)); 
     } 
    } 
    req.send(null); 
} 
JSONCallback = function(JSONObj){ 
    alert(JSONObj); 
}; 
GET_JSON(JSONCallback); 
} 
+1

您不需要使用window.open或iframe來請求JSON。您將需要使用XMLHttpRequest對象,並希望它們支持CORS,因爲有相同的源策略。如果沒有,希望他們支持JSONP。 – epascarello

+1

您需要使用AJAX,並在'onreadystatechange'函數中調用'JSON.parse'並將您想要的內容寫入新窗口。由於AJAX同源策略,您可能無法執行此操作,因此您可能需要在服務器上使用代理功能。 – Barmar

+0

爲什麼使用iFrame來代替AJAX調用?你確定他們的API允許跨域請求嗎?如果他們不這樣做,那麼您需要在服務器上使用代理腳本。 –

回答

0

如果wunderground使用相同類型的API爲wiki media的不知道。然而,下面是一個例子,你將如何執行JSONP(在這裏閱讀:JSONP),它可以讓你查詢一個頁面,儘管有跨域請求。

如果您閱讀此問題:Trying to search wunderground locations with javascript, jquery, and html,您可以看到建議使用JSONP。因此,對以下示例的一個小修改將使您開始着手如何從網站獲取結果。

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Wikipedia JSON Grabber</title> 
     <meta charset="UTF-8"> 
     <meta name="viewport" content="width=device-width"> 
     <style> 
     div{ 
      position: relative; 
      background-color: white; 
     } 
     </style> 
     <script> 
     // Function call the Wikipedia API 
     function doFetch() { 
      var tmpScript = document.createElement("script"); 
      tmpScript.src = "http://en.wikipedia.org/w/api.php?" + 
        "format=json" + 
        "&callback=gotFetch" + 
        "&action=query" + 
        "&titles=json" + 
        "&prop=revisions" + 
        "&rvprop=content"; 
      document.body.appendChild(tmpScript); 
     } 

     // Callback to trigger whenever the API responds 
     function gotFetch(data) { 
      var parent = document.createElement("div"), 
        depth = 0; 
      document.body.appendChild(parent); 
      console.log("Got data"); 
      for (var t in data) { 
       console.log(data[t]); 
       printData(data, parent, depth); 
      } 
     } 

     // Recursively print out the object received to console 
     function printData(data, parent, depth) { 
      for (var prop in data) { 

       var newDiv = document.createElement("div"); 
       newDiv.style.left = (10 * (depth++)) + "px"; 
       parent.appendChild(newDiv); 

       if (typeof data[prop] === "object") { 
        newDiv.innerHTML = prop; 
        printData(data[prop], newDiv, depth); 
       } else { 
        newDiv.innerHTML = data[prop]; 
       } 
      } 
     } 

     function main() { 
      doFetch(); 
     } 
     </script> 
    </head> 
    <body onload="main();"> 
     <div></div> 
    </body> 
</html> 
0

我從wunderground樣本JSON網址:

var url = "http://api.wunderground.com/api/<API_KEY>/conditions/q/CA/San_Francisco.json"; 

其輸出JSON是:

{"response":{"version":"0.1","termsofService":"http://www.wunderground.com/weather/api/d/terms.html","features":{"conditions":1}},"current_observation":{"image":{"url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png","title":"Weather Underground","link":"http://www.wunderground.com"},"display_location":{"full":"San Francisco, CA","city":"San Francisco","state":"CA","state_name":"California","country":"US","country_iso3166":"US","zip":"94101","magic":"1","wmo":"99999","latitude":"37.77500916","longitude":"-122.41825867","elevation":"47.00000000"},"observation_location":{"full":"SOMA - Near Van Ness, San Francisco, California","city":"SOMA - Near Van Ness, San Francisco","state":"California","country":"US","country_iso3166":"US","latitude":"37.773285","longitude":"-122.417725","elevation":"49 ft"},"estimated":{},"station_id":"KCASANFR58","observation_time":"Last Updated on January 15, 12:12 PM PST","observation_time_rfc822":"Wed, 15 Jan 2014 12:12:06 -0800","observation_epoch":"1389816726","local_time_rfc822":"Wed, 15 Jan 2014 12:12:10 -0800","local_epoch":"1389816730","local_tz_short":"PST","local_tz_long":"America/Los_Angeles","local_tz_offset":"-0800","weather":"Partly Cloudy","temperature_string":"69.8 F (21.0 C)","temp_f":69.8,"temp_c":21.0,"relative_humidity":"28%","wind_string":"From the WNW at 2.0 MPH","wind_dir":"WNW","wind_degrees":295,"wind_mph":2.0,"wind_gust_mph":0,"wind_kph":3.2,"wind_gust_kph":0,"pressure_mb":"1026","pressure_in":"30.29","pressure_trend":"-","dewpoint_string":"35 F (2 C)","dewpoint_f":35,"dewpoint_c":2,"heat_index_string":"NA","heat_index_f":"NA","heat_index_c":"NA","windchill_string":"NA","windchill_f":"NA","windchill_c":"NA","feelslike_string":"69.8 F (21.0 C)","feelslike_f":"69.8","feelslike_c":"21.0","visibility_mi":"10.0","visibility_km":"16.1","solarradiation":"--","UV":"3","precip_1hr_string":"0.00 in (0 mm)","precip_1hr_in":"0.00","precip_1hr_metric":" 0","precip_today_string":"0.00 in (0 mm)","precip_today_in":"0.00","precip_today_metric":"0","icon":"partlycloudy","icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif","forecast_url":"http://www.wunderground.com/US/CA/San_Francisco.html","history_url":"http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KCASANFR58","ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=37.773285,-122.417725"}} 

那麼現在我們如何想獲得這個輸出!?我們有2個不同的解決方案:

1-舊解決方案是使用AJAX來獲取JSON作爲一個字符串,然後解析它作爲一個對象,像這樣:

GET_JSON = function(callback){ 
    var req = new XMLHttpRequest(); 
    req.open("GET", url, true); 
    req.onreadystatechange = function(){ 
     if(this.readyState==4){ 
      callback(JSON.parse(req.responseText)); 
     } 
    } 
    req.send(null); 
} 
JSONCallback = function(JSONObj){ 
    alert(JSONObj); 
}; 
GET_JSON(JSONCallback); 

但這裏的問題是,如果你這樣做,在你的網站,你將面臨與此錯誤:

No 'Access-Control-Allow-Origin' header is present on the requested resource. 
    Origin 'http://mydomain.com' is therefore not allowed access. 

2-沒問題,wunderground weather api支持JSONP,它會幫助我們解決這個問題,我們必須只需打個電話JSONP,棘手的點這裏是的,我們不會使用定期ajax解決方案了:

GET_JSON = function(callback){ 
    var script = document.createElement("script"); 
    script.type = "text/javascript"; 
    script.src = url + "?callback=" + callback; 
    document.body.appendChild(script); 
} 
window.JSONCallback = function(JSONObj){ 
    alert(JSONObj); 
}; 
GET_JSON("JSONCallback"); 

有一個非常棘手的一點是非常重要的。如果您檢查最後一行而不是將回調對象作爲參數傳遞,我已經傳遞了它的名稱,爲什麼?

答案是,如果我們想要有一個JSONP調用,我們必須將0123.queryString的回調函數名稱傳遞給它。像這樣:

url = "http:// ... .json?callback=JSONCallback"; 

,這是所有你需要知道要訪問您的JSON對象,沒有你需要解析的字符串。

+0

感謝您爲幫助我而努力。然而,我不確定如何實施你的建議。我更新了現在在主文章中的腳本。我現在需要解決什麼問題? – user2941841

+0

你已經在你的代碼中混合了ajax調用和jsonp,如果你用我的第二個GET_JSON替換GET_JSON(不使用XmlHttpRequest),你的問題就解決了。 –