2015-11-27 60 views
0

我是新來的AJAX和jQuery編程。我正在設計網站上顯示某個城市天氣的天氣網絡應用程序。我已經能夠成功地在網站上顯示天氣。但是現在我想從JSON獲取溫度並將其轉換爲華氏溫度。這裏是我的web應用程序JavaScript的JSON AJAX數據解析

 $(function(){ 


    $('#clickme').click(function() { 
     $("#weather").empty(); 

     var search_City2 = $("#c1").val(); 

     $.ajax({ 
      url: 'http://localhost:3000/?id='+search_City2, 
      dataType: 'json', 
      success: function(data) { 
      var items = []; 

      $.each(data, function(key, val) { 

       items.push('<li id="' + key + '">' + key + ' : '+ val + '</li>'); 

      }); 

      $('<ul/>', { 
       'class': 'weather-list', 
       html: items.join('') 
      }).appendTo('#weather'); 
      var city = search_City2; 


      }, 
     statusCode: { 
      404: function() { 
       alert('There was a problem with the server. Try again soon!'); 
      } 
      } 
     }); 
    }); 
}); 

下面的代碼是我JSON數據

{ text: 'Light Rain', 
    temp: '12', 
    date: 'Fri, 27 Nov 2015 11:00 am EST', 
    high: '14', 
    low: '-2' } 
+0

看到這個答案:http://stackoverflow.com/questions/23310353/how-to-read-json-result-in-jquery/ 23310376#23310376 –

+0

是什麼'console.dir(jQuery.parseJSON(數據));'在你成功的功能產生? –

+0

在控制檯登錄這是「空」 –

回答

0

試試吧。

var jsObj = jQuery.parseJSON(data); // Convert string JSON to object 

if (jsObj.temp) { 

    var temp = parseFloat(jsObj.temp.toString()); 
    var tempFahrenheit = temp * 33.8; // 1 Celcuis = 33.8 Fahrenheit 

    console.log('Temperature: ' + tempFahrenheit + 'ºF'); 
} 
+0

收到錯誤「遺漏的類型錯誤:無法讀取空的特性‘溫度’,」如果條件變更爲「如果(jsObj && jsObj.temp)」 –

+0

不記錄任何東西到控制檯這是我得到什麼時,我調試它「jsObj = null,temp = u ndefine」 –

+0

它運行我的腳本,但確實 –

0

這是工作代碼...

<!DOCTYPE html> 
<html> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
</head> 
<body> 
    <script> 
     $(document).ready(function(){ 
      var data = { text: 'Light Rain', 
         temp: '12', 
         date: 'Fri, 27 Nov 2015 11:00 am EST', 
         high: '14', 
         low: '-2' }; 

      $.each(data, function (k, v) { 
       if(k == 'temp'){ 
        var cToFahr = v * 9/5 + 32; 
        console.log(v, cToFahr); 
       } 
      }); 
    }); 
    </script> 
</body> 
</html>