如何将变量传递给JSON查询字符串

时间:2017-11-19 14:01:33

标签: json

我创建了以下代码,并希望从下拉列表中传递一个城市名称,而下拉列表则会显示该城市的温度:

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>


        $(document).ready(function () {
            document.getElementById('cityName').value;
         //   localStorage.setItem('City_Name', city);

            //-------------------------
            var searchtext = "select item.condition from weather.forecast where woeid in (select woeid from geo.places(1) where text='" + city + "') and u='c'"
            //change city variable dynamically as required
            $.getJSON("https://query.yahooapis.com/v1/public/yql?q=" + searchtext + "&format=json").success(function (data) {
                console.log(data);
                $('#temp').html("Temperature in " + city + " is " + data.query.results.channel.item.condition.temp + "°C");
              //  localStorage.setItem('tempr', data.query.results.channel.item.condition.temp);
            //-------------------------

            });
        });

</script>

当我在代码中手动输入城市名称时,它会起作用,但是当我传递变量的值时会失败。

1 个答案:

答案 0 :(得分:0)

我希望它适合你。 我试过了它的工作

示例输出

  

孟买的气温是27°C

仔细看看这一行 你拿城市名称,但没有用“var”

来定义
  

var city = document.getElementById('cityName')。value;

$(document).ready(function () {
    var city = document.getElementById('cityName').value;
    //   localStorage.setItem('City_Name', city);

    //-------------------------
    var searchtext = "select item.condition from weather.forecast where woeid in (select woeid from geo.places(1) where text='"+city+"') and u='c'";
    //change city variable dynamically as required
    //https://query.yahooapis.com/v1/public/yql?q=select item.condition from weather.forecast where woeid in (select woeid from geo.places(1) where text='New York') and u='c'&format=json
    $.getJSON("https://query.yahooapis.com/v1/public/yql?q=" + searchtext + "&format=json").success(function (data) {
        console.log(data);
        $('#temp').html("Temperature in " + city + " is " + data.query.results.channel.item.condition.temp + "°C");
        //  localStorage.setItem('tempr', data.query.results.channel.item.condition.temp);
        //-------------------------

    });
});