Javascript 用JSON文件中的变量(字符串)填充文本区域

Javascript 用JSON文件中的变量(字符串)填充文本区域,javascript,html,Javascript,Html,当用户按下按钮时,我需要程序使用API(JSON)中的字符串变量填充文本字段 以下是我所拥有的,但它不起作用: <label for="weatherYVR"></label> <input name="weatherYVR" type="text" id="weatherYVR" value="" size="45" /> <button onclick="weatherYVR">YVR Weather</button> <s

当用户按下按钮时,我需要程序使用API(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>

YVR天气
函数weatherYVR(){
函数fillText(x){
document.getElementById(“weatherYVR”)。值=x
}
jQuery(文档).ready(函数($){
$.ajax({
url:“http://api.wunderground.com/api/XXXXXAPIKEYXXXXXX/geolookup/conditions/q/YVR.json",
数据类型:“jsonp”,
成功:函数(已解析的_json){
var location=parsed_json['location']['city'];
var weather=parsed_json['current_observation']['wind_string'];
填充文字(天气)
}
});
});
}

我在您的代码中修复了一些东西。由于您使用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>

YVR天气
函数weatherYVR(){
jQuery.ajax({
url:“http://api.wunderground.com/api/XXXXXAPIKEYXXXXXX/geolookup/conditions/q/YVR.json",
数据类型:“jsonp”,
成功:函数(已解析的_json){
var location=parsed_json['location']['city'];
var weather=parsed_json['current_observation']['wind_string'];
jQuery('#weatherYVR').val(天气);
}
});
}
代码中存在一些差异,例如将jQuery标识符从
$
更改为
jQuery
。此外,函数的结构有点不合理。例如,行
jQuery(document).ready(函数($){…})在文档完全加载时运行,那么为什么要在函数内部执行此操作?另外,
fillText()
的函数声明有点不必要,而且如果不是不正确的话,它的定义位置是非正统的javascriptEDIT:它可以工作,但是是。只要看一下文档就知道了。总的来说,你的想法似乎是对的