weixin_33738578 2018-09-02 13:19 采纳率: 0%
浏览 32

用户输入的API查询

I have a form where user types in the city name, I want to make an API call and get weather results in that city and then display it in the console.

I'm getting an error because for some reason the variable that holds input.value is not being concatenated into the string.

Here's the code:

var request;
var input1 = document.getElementById('city');
var api = 'https://api.openweathermap.org/data/2.5/weather?q=';
var apikey = '&APPID=433b12b793d7ebc17989745c069a540b';
var sum = api + input1.value + apikey;

function myFunction() {

  request = new XMLHttpRequest();

  request.open('GET', sum, true);
  request.onload = function() {

    var data = JSON.parse(this.response);
    if (request.status >= 200 && request.status < 400) {
      console.log(data);
    } else {
      console.log(input1.value);
    }
  }

  request.send();
}
myFunction(input1.value);
<input id='city' value='San Francisco'>

Thanks for any help!

</div>
  • 写回答

1条回答 默认 最新

  • from.. 2018-09-02 13:25
    关注

    Your code is ok, you just need to put everything inside the function.

     <script>
        function myFunction() {
    
            var request;
            var input1 = document.getElementById('city');
            var api = 'https://api.openweathermap.org/data/2.5/weather?q=';
            var apikey =
                '&APPID=433b12b793d7ebc17989745c069a540b';
            var sum = api + input1.value + apikey;
    
            request = new XMLHttpRequest();
    
            request.open('GET', sum, true);
            request.onload = function () {
    
                var data = JSON.parse(this.response);
                if (request.status >= 200 && request.status < 400) {
                    console.log(data);
                } else {
                    console.log(input1.value);
                }
            }
    
            request.send();
        }
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!