2015-04-06 73 views
0

當用戶按下按鈕時,我需要程序使用API​​(JSON)中的字符串變量填充文本字段。使用JSON文件中的變量(字符串)填充文本區域

這裏是我有什麼,但它不工作:

<label for="weatherYVR"></label> 
<input name="weatherYVR" type="text" id="weatherYVR" value="" size="45" /> 

<button onclick="weatherYVR">YVR Weather</button> 
<script> 
function weatherYVR() { 

    function fillText(x) { 
     document.getElementById("weatherYVR").value = x 
    } 

    jQuery(document).ready(function($) { 
     $.ajax({ 
      url : "http://api.wunderground.com/api/XXXXXAPIKEYXXXXXX/geolookup/conditions/q/YVR.json", 
      dataType : "jsonp", 
      success : function(parsed_json) { 
       var location = parsed_json['location']['city']; 
       var weather = parsed_json['current_observation']['wind_string']; 
       fillText(weather) 
      } 
     }); 
    }); 
} 
</script> 

回答

2

我在你的代碼搞掂了幾件事情。由於你使用jQuery,我排除了一些基本的javascript,並將其替換爲jQuery對應。

<label for="weatherYVR"></label> 
    <input name="weatherYVR" type="text" id="weatherYVR" value="" size="45" /> 

    <button onclick="weatherYVR()">YVR Weather</button> 
    <script> 

    function weatherYVR() { 
     jQuery.ajax({ 
      url : "http://api.wunderground.com/api/XXXXXAPIKEYXXXXXX/geolookup/conditions/q/YVR.json", 
      dataType : "jsonp", 
      success : function(parsed_json) { 
       var location = parsed_json['location']['city']; 
       var weather = parsed_json['current_observation']['wind_string']; 
       jQuery('#weatherYVR').val(weather); 
      } 
     }); 
    } 
    </script> 

你必須在你的代碼存在一些差異,比如改變jQuery的標識,從$jQuery。另外,你的功能結構有點偏離。例如,行jQuery(document).ready(function($) {...});在文件完全加載時運行,所以爲什麼要在函數內部執行此操作? fillText()函數聲明是有點不必要的,它的位置定義是非傳統的如果不是不合適的javascript編輯:它的工作,但是a bit wonky as described here。只要看看文檔就可以瞭解一些事情。總的來說,你似乎有正確的想法。