我有一个按钮,当事件点击时我从JSON获得返回值。然后我想显示来自对象JSON的特定数据。如何实现我的代码?我在其他论坛中搜索,我得到这个链接以在JSON中查找对象,但这在我的代码中不起作用。
这是我从Firebug获得的JSON结果:
{ "rajaongkir": {
"query": {
"origin": "501",
"destination": "114",
"weight": 1700,
"courier": "jne"
},
"status": {
"code": 200,
"description": "OK"
},
"origin_details": {
"city_id": "501",
"province_id": "5",
"province": "DI Yogyakarta",
"type": "Kota",
"city_name": "Yogyakarta",
"postal_code": "55222"
},
"destination_details": {
"city_id": "114",
"province_id": "1",
"province": "Bali",
"type": "Kota",
"city_name ": "Denpasar",
"postal_code": "80227"
},
"results": [
{
"code": "jne",
"name": "Jalur Nugraha Ekakurir (JNE)",
"costs": [
{
"service": "OKE",
"description": "Ongkos Kirim Ekonomis",
"cost": [
{
"value": 42000,
"etd": "4-5",
"note": ""
}
]
},
{
"service": "REG",
"description": "Layanan Reguler",
"cost": [
{
"value": 48000,
"etd": "2-3",
"note": ""
}
]
},
{
"service": "YES",
"description": "Yakin Esok Sampai",
"cost": [
{
"value": 104000,
"etd": "1-1",
"note": ""
}
]
},
{
"service": "SPS",
"description": "Super Speed",
"cost": [
{
"value": 367000,
"etd": "",
"note": ""
}
]
},
{
"service": "JTR",
"description": "JNE Trucking",
"cost": [
{
"value": 50000,
"etd": "",
"note": ""
}
]
},
{
"service": "JTR250",
"description": "JNE Trucking",
"cost": [
{
"value": 1350000,
"etd": "",
"note": ""
}
]
},
{
"service": "JTR<150",
"description": "JNE Trucking",
"cost": [
{
"value": 500000,
"etd": "",
"note": ""
}
]
},
{
"service": "JTR>250",
"description": "JNE Trucking",
"cost": [
{
"value": 1900000,
"etd": "",
"note": ""
}
]
}
]
}
]
}
}
然后,我只想将此对象显示给我的div "value":48000"
或标准服务:Reg。
这是我的jQuery:
$("#hitungJNE").click(function () {
$.ajax({
cache: false,
type: 'POST',
url: 'cost.php',
data: {
isHapus : 0
},
dataType: 'json',
success: function(isSuccess)
{
var test = getObjects(isSuccess, 'service', 'REG');
$('#myDiv').text(test);
//i want set this value ex: $('#myDiv').text(48000);
}
});
});
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
我已阅读此链接use jQuery's find() on JSON object但不适合我。