如何在yahoo weather中将变量分配到javascript src脚本中

How to assign a variable into a javascript src script in yahoo weather

本文关键字:分配 javascript 脚本 src 变量 yahoo weather      更新时间:2023-09-26

以下代码运行良好,但我正试图让它从html表单接收输入,以便从表单中选择任何位置。请参阅:text='hicago,il'我希望它接收变量text='location'

<script>
  var callbackFunction = function(data) {
    var wind = data.query.results.channel.wind;
    alert(wind.chill);
  };
</script>
<script src="https://query.yahooapis.com/v1/public/yql?q=select wind from weather.forecast where woeid in (select woeid from geo.places(1) where text='chicago, il')&format=json&callback=callbackFunction"></script>

我的一些尝试:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <script>
            function getLocation() {
                var city = document.getElementById("city").value;
                var country = document.getElementById("country").value;
                var location = city + "," + country;
                //alert(location);
            }
            var callbackFunction = function(data) {
                var wind = data.query.results.channel.wind;
                document.write(wind.chill)  
                alert(wind.chill);
                };

        </script>
    <script src="https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='location')&format=json&callback=callbackFunction"></script>
    </head>

    <body>
        <input type="text" id="city">
        <input type="text" id="country"
        <button onclick="getLocation()">Get Weather</button>
    </body>
</html>

我也尝试过其他方法,但即使我直接给var location分配一个字符串,比如location="new york,ny"或"'''new york,ny'''"等,它也不会返回值。请帮忙,谢谢。

基本上,您需要在从表单中获取值后加载yahooapis脚本。现在,该脚本只会在页面加载时加载,这将不起作用。幸运的是,您可以使用javascript将脚本元素添加到页面中。

function getLocation() {
   var city = document.getElementById("city").value;
   var country = document.getElementById("country").value;
   var location = city + "," + country;
    //create a script and add it to your page
    var script = document.createElement('script');
    script.src = "https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='" + location + "')&format=json&callback=callbackFunction";
    document.getElementsByTagName('head')[0].appendChild(script);
}