从对象jQuery检索数据时遇到了一些问题。我将一些数据作为对象,一些数据来自jquery ajax。
如果记录数据,数据就在那里,但是当我尝试获取数据时,日志表示未定义,但是当我尝试获取另一个数据时,日志会抛出数据。例如:
console.log(v);
console.log(v.totalOngkir);
将输出如下:
v
的输出,如果它展开:
v
表示它有totalOngkir
,但当我想从v.totalOngkir
取出时,它说undefined
。但是当我试图从v
获取另一个值时,通常显示它。
P.S。我正在使用$.when
等待ajax的结果,
这是我的代码:
$(document).ready(function(){
var listCart = {};
function formatDigit(str){
return str.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.");
}
function cekOngkir(weight,origin,destination,kurir,servis) {
return $.ajax({
url:"/courier/cekongkir",
type:"POST",
data:"weight="+weight+"&origin="+origin+"&destination="+destination+"&kurir="+kurir+"&servis="+servis,
success:function(e){}
});
}
function listEachCart(i,e){
var totalWeight = 0;
var totalPrice = 0;
$(e).find(".theProduct").map(function(i1,e1){
totalWeight += parseFloat($(e1).attr("totalBerat"));
totalPrice += parseInt($(e1).attr("totalHarga"));
});
var tempArray = {};
tempArray['totalWeight'] = totalWeight;
tempArray['totalPrice'] = totalPrice;
$.when(cekOngkir(tempArray.totalWeight,listCart[i].kecamatanToko,listCart[i].kecamatanUser,listCart[i].kodeKurir,listCart[i].kodeServis)).done(function(es){
tempArray['totalOngkir'] = parseInt(es);
// console.log(es);
});
listCart[i] = Object.assign(tempArray,listCart[i]);
// console.log(listCart[i]);
}
var deferredArr =
$(".listCart").map(function(i,e){
var listGroup = {};
listGroup['idToko'] = $(e).attr("idToko");
listGroup['idUsersAlamat'] = $(e).attr("idUsersAlamat");
listGroup['kecamatanToko'] = $(e).attr("kecamatanToko");
listGroup['kecamatanUser'] = $(e).attr("kecamatanUser");
listGroup['idKurir'] = $(e).attr("idKurir");
listGroup['kodeKurir'] = $(e).attr("kodeKurir");
listGroup['kodeServis'] = $(e).attr("kodeServis");
listGroup['element'] = e;
listCart[i] = listGroup;
listEachCart(i,e);
});
$.when.apply(this,deferredArr).then(function(){
$.map(listCart,function(v,i){
console.log(Object.keys(v));
console.log(v.totalOngkir);
// $(v.element).find(".totalOngkir").html("Rp. "+formatDigit((v.totalOngkir).toString()));
});
});
});