[英]How to access data from "Passthrough" object returned after API call?
[英]How to access data returned from an API using jQuery
我正在向 API 發出 AJAX GET 請求,該請求返回我所在地區提供快遞的所有商店。 我需要檢查數據以查看該地區是否有任何商店提供快遞但無法正確訪問數據以執行任何檢查並且不明白為什么。
從 API 返回的數據的剝離版本如下:
{
"data": {
"service_eligibility": [
{
"accesspoint_list": [
{
"current_time": null,
"currency": null,
"accesspoint_id": "3242342-6dc1-43d8-b3d0-234234234234",
"service_info": {
"fulfillment_type": "DELIVERY",
"reservation_type": "SLOTS",
"dispense_type": "DELIVERY",
"priority": 0,
"carrier": "Owned",
"fulfillment_option": "DELIVERY",
"location_type": "Home",
"service_time": 0,
"is_recurring_slot": false,
"enable_express": false,
"is_unattended_slot": true,
"is_flex_slot": false
},
{
"current_time": null,
"currency": null,
"accesspoint_id": "234234242-3387-4e1d-9eaa-234234242",
"service_info": {
"fulfillment_type": "INSTORE_PICKUP",
"reservation_type": "SLOTS",
"dispense_type": "PICKUP_INSTORE",
"priority": 0,
"carrier": "NA",
"fulfillment_option": "PICKUP",
"location_type": "Store",
"service_time": 0,
"is_recurring_slot": false,
"enable_express": true,
"is_unattended_slot": false,
"is_flex_slot": false
},
"current_time": "2021-06-07T11:24:39Z",
"currency": "GBP"
},
"status_code": 200,
"status_message": "Requested input executed successfully."
}
我用來獲取數據的調用:
$.ajax({
type: 'GET',
dataType: "json",
url: query,
data: "",
success: function(data)
{
//Check for express delivery
if(data.status_code == 200) {
console.log(data);
}
},
error: function(data)
{
//Check for API error
if(data.status == 400){
console.log(data.responseJSON.errors[0].message);
}
}
})
到目前為止,數據正在記錄到控制台。 但是當我嘗試訪問它或我想使用的部分時,我得到了控制台錯誤。
我嘗試從控制台復制屬性路徑並在 console.log 中使用它: console.log(data.service_eligibility[0].accesspoint_list)
但收到錯誤消息: Cannot read property '0' of undefined
我只嘗試了data.service_eligibility
但這只是給了我undefined
的錯誤
事實上,即使我只是嘗試訪問data.currency
我得到undefined
為什么我無法訪問從 API 返回的數據?
type: 'GET',
dataType: "json",
url: query,
data: "",
success: function(data)
{
//Check for express delivery
if(data.status_code == 200) {
console.log(response.data.ervice_eligibility[0].accesspoint_list);
}
}
查看您提供的上述代碼段,您在成功處理程序中接收的data
object 看起來並不直接引用您收到的響應中的data
object。 由於名稱相同,因此可能會造成混淆。 我認為如果您嘗試使用data.data.service_eligibility
訪問data
object 中的屬性,您將能夠訪問它。 為了更清楚,請參見下面的代碼:
type: 'GET',
dataType: "json",
url: query,
data: "",
success: function(response)
{
//Check for express delivery
if(response.status_code == 200) {
console.log(response.data.service_eligibility[0].accesspoint_list);
}
}
想想看,如果你的數據在success handler里面是可用的,就說明從api獲取數據的異步動作已經成功完成。 您可以只調試數據 object 的結構,並找出您訪問值的方式中缺少什么或有什么問題。 人們可以表現不同,代碼永遠不會::)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.