无法弄清楚为什么我无法从API检索数据

时间:2020-10-30 07:53:47

标签: javascript ajax api

当我在搜索栏中输入城市名称时,它应该会提取有关该城市天气的信息,但出现400错误的请求错误
JAVASCRIPT:

function handleGetData(event){
        event.preventDefault();
        
        const cityName = $("#city").val()
        $.ajax({url: `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=imperial&appid=99df413c60279878184277e08a2c6863`})
        .then(
            (data) => {
                console.log(data);
                $("#name").text(data.name)
                $("#temp").text(data.temp)
                $("#feels").text(data.feels_like)
                $("#weather").text(data.weather)
                
            },
            (error) => {
                console.log("bad request: ", error)
            }
            )
            console.log("It's working!")
    }
    $('form').on("submit", handleGetData)

1 个答案:

答案 0 :(得分:0)

您使用的诺言不正确。 正确的语法是.then(result => {}).catch(e => {})

const cityName = $("#city").val()
$.ajax({url: url})
   .then((data, a, b, c) => {
      console.log(data);
      $("#name").text(data.name)
      $("#temp").text(data.temp)
      $("#feels").text(data.feels_like)
      $("#weather").text(data.weather)
      console.log("It's working!")
   })
   .catch(error => {
      console.error(error) //not necessarily a "bad request"
   })