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>
    
    评论

报告相同问题?