简体   繁体   中英

How to filter API values based on user input using jQuery

How do I change the city(q) equals London to New York, based on user input field?

Scenario: User enter the city name and temperature will be displayed according to the city name.

 $.getJSON('https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid={key}', function(data){


});

I tried the below code. but couldn't get the expected result.

$(function(){

$(".submit_btn").on('click', function(){
    var city = $("#city_name").val();

    $.getJSON('https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid={key}', function(data){

    var temp = `Temperature: ${data.main.temp} degrees Celsius`

    $(".w1").text(temp);



    });


});
});

Finally, it worked as follows;

$.getJSON(`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid={key}`, function(info){

var temp = `Temperature: ${info.main.temp} degrees Celsius`

$(".w1").text(temp);
});

Solution: Add backticks (`) to either side of the URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM