首页 > 解决方案 > 如何使用 jQuery 根据用户输入过滤 API 值

问题描述

如何根据用户输入字段将城市(q)等于伦敦更改为纽约?

场景:用户输入城市名称,根据城市名称显示温度。

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


});

我尝试了下面的代码。但无法得到预期的结果。

$(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);



    });


});
});

标签: jquerystringapiformat

解决方案


最后,它的工作方式如下;

$.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);
});

解决方案:在 URL 的任一侧添加反引号 (`)。


推荐阅读