现在我想在循环中获取数组数据。
{
"rajaongkir": {
"query": {
"origin": "23",
"destination": "152",
"weight": 1500,
"courier": "all"
},
"status": {
"code": 200,
"description": "OK"
},
"origin_details": {
"city_id": "23",
"province_id": "9",
"province": "Jawa Barat",
"type": "Kota",
"city_name": "Bandung",
"postal_code": "40000"
},
"destination_details": {
"city_id": "152",
"province_id": "6",
"province": "DKI Jakarta",
"type": "Kota",
"city_name": "Jakarta Pusat",
"postal_code": "10000"
},
"results": [
{
"code": "pos",
"name": "POS Indonesia (POS)",
"costs": [
{
"service": "Surat Kilat Khusus",
"description": "Surat Kilat Khusus",
"cost": [
{
"value": 16500,
"etd": "2-4",
"note": ""
}
]
},
{
"service": "Express Next Day",
"description": "Express Next Day",
"cost": [
{
"value": 22000,
"etd": "1",
"note": ""
}
]
}
]
},
{
"code": "jne",
"name": "Jalur Nugraha Ekakurir (JNE)",
"costs": [
{
"service": "OKE",
"description": "Ongkos Kirim Ekonomis",
"cost": [
{
"value": 18000,
"etd": "2-3",
"note": ""
}
]
},
{
"service": "REG",
"description": "Layanan Reguler",
"cost": [
{
"value": 20000,
"etd": "1-2",
"note": ""
}
]
},
{
"service": "YES",
"description": "Yakin Esok Sampai",
"cost": [
{
"value": 30000,
"etd": "1-1",
"note": ""
}
]
}
]
},
{
"code": "tiki",
"name": "Citra Van Titipan Kilat (TIKI)",
"costs": [
{
"service": "SDS",
"description": "Same Day Service",
"cost": [
{
"value": 135000,
"etd": "",
"note": ""
}
]
},
{
"service": "HDS",
"description": "Holiday Delivery Service",
"cost": [
{
"value": 49000,
"etd": "",
"note": ""
}
]
},
{
"service": "ONS",
"description": "Over Night Service",
"cost": [
{
"value": 26000,
"etd": "",
"note": ""
}
]
},
{
"service": "REG",
"description": "Regular Service",
"cost": [
{
"value": 17000,
"etd": "",
"note": ""
}
]
},
{
"service": "ECO",
"description": "Economi Service",
"cost": [
{
"value": 14000,
"etd": "",
"note": ""
}
]
}
]
}
]
}
}
我试图获取数组数据并将其附加到组合框。结果是数据显示全部为双/重复。
这是获取数组数据的JS:
$.ajax({
type : 'POST',
url : 'cek_ongkir.php',
dataType: "JSON",
data : {'kab_id' : kab, 'kurir' : kurir, 'asal' : asal, 'berat' : berat},
success: function (jsonStr) {
$.each(jsonStr['rajaongkir']['results'], function(i,n)
{
var len = n['costs'].length;
for(var i=0; i<len; i++)
{
cou = '<option value="'+n['costs'][0]['cost'][0]['value']+'">'+n['costs'][0]['description']+'</option>';
cou = cou + '';
$("#service").append(cou);
}
});
$("#service").prop('disabled', false);
}
});
我不知道我需要将[i]
放在该循环上。
答案 0 :(得分:1)
您需要i
才能访问costs
数组的每个对象。
<强>替换强>
cou = '<option value="'+n['costs'][0]['cost'][0]['value']+'">'+n['costs'][0]['description']+'</option>';
<强>与强>
cou = '<option value="'+n['costs'][i]['cost'][0]['value']+'">'+n['costs'][i]['description']+'</option>';
由于您在循环中使用n['costs'][0]
因此它将始终返回costs
数组的第一个对象,这就是您的选项重复的原因。要在循环内访问数组的每个对象,必须使用从数组的0
到length-1
的循环中获得的数组的索引。因此,您必须在代码中使用n['costs'][i]
才能使其按预期工作。