簡體   English   中英

對來自 function ajax 請求的未定義響應做出反應

[英]react undefined response from function ajax request

您好為什么它的響應“未定義回調”

組件 1:

console.log(getUserGps());

組件 2:

import $ from 'jquery'
export const getUserGps = () => {
    $.ajax({
        url: "https://geolocation-db.com/jsonp",
        jsonpCallback: "callback",
        dataType: "jsonp",
        success: function(location:any) {
            let city = location.city
            console.log('Pobrano z gps ' + location.city)
            return city
        }
      })
}
jsonpCallback: "callback",

您明確告訴 jQuery 告訴服務器生成一個 JSONP 程序,該程序調用名為callback的 function 。

您沒有定義 function。


刪除該行。 讓 jQuery 使用自動名稱從success屬性生成 function。

您在這里遇到的問題是,您的 aync function 沒有返回值。 您可以執行以下操作:

const getUserGps = () => {
  return $.ajax({
    url: "https://geolocation-db.com/jsonp",
    jsonpCallback: "callback",
    dataType: "jsonp",
  }).then((location) => {
    return location.city
  })
}

在這里,您將請求作為 promise 返回,然后您可以在第二個組件中執行以下操作:

getUserGps().then(data => {
   console.log(data);
})

在這里,您可以獲得有關異步函數和承諾如何工作的更多信息: https://www.w3schools.com/Js/js_promise.asp

暫無
暫無

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

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