【发布时间】:2021-08-24 17:45:42
【问题描述】:
我正在向 API 发出 AJAX GET 请求,该 API 返回我所在地区提供快递的所有商店。我需要检查数据以查看该地区是否有任何商店提供快递但无法正确访问数据以执行任何检查并且不明白为什么。
从 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 返回的数据?
【问题讨论】:
-
试试:
data.data.service_eligibility[0].accesspoint_list -
那行得通,为什么我必须输入
data.data? -
因为返回响应在
data变量内,而您的accesspoint_list嵌套如下:data > service_eligibility > accesspoint_list
标签: javascript jquery arrays json api