簡體   English   中英

無法弄清楚為什么我無法從我的 API 中檢索數據

[英]Cant figure out why I cant retrieve data from my API

當我在搜索欄中輸入城市名稱時,它應該會顯示該城市的天氣信息,但出現 400 bad request 錯誤
爪哇腳本:

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)

您錯誤地使用了承諾。 正確的語法是.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"
   })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM