我有一个返回JS对象的AJAX函数。但是当我为函数分配var时,我得到了undefined。在FireBug中调试,一切都很好,除非我尝试将结果分配给 var tester
这是我的代码......
function AllBidData(HighestBid,MinimumBid,HighestProxyBid) {
return {
HighestBid: HighestBid,
MinimumBid: MinimumBid,
HighestProxyBid: HighestProxyBid
};
}
function GetAllBidData() {
$.ajax({
type: "POST",
dataType: "json",
url: "/VehicleAuction/GetAllBidData",
data: { AuctionID: AuctionID, UserID: UserID }
}).done(function (msg) {
var BidDate = new AllBidData(msg.HighestBid, msg.MinimumBid, msg.HighestProxyBid);
return BidDate;
});
}
var tester = GetAllBidData();
//why is tester is undefined?
更新&解决方案 - 这就是我解决这个问题的方法 - 使用延迟对象
function GetAllBidData() {
return $.ajax({
type: "POST",
dataType: "json",
url: "/VehicleAuction/GetAllBidData",
data: { AuctionID: AuctionID, UserID: UserID }
});
}
function AllBidData(data) {
return {
HighestBid: data.HighestBid,
MinimumBid: data.MinimumBid,
HighestProxyBid: data.HighestProxyBid
};
}
var tester = null;
tester = GetAllBidData().done(AllBidData);
答案 0 :(得分:0)
这是异步调用。该函数在ajax调用发生之前执行并返回值
function GetAllBidData(callback) {
$.ajax({
type: "POST",
dataType: "json",
url: "/VehicleAuction/GetAllBidData",
data: { AuctionID: AuctionID, UserID: UserID }
}).done(function (msg) {
var BidDate = new AllBidData(msg.HighestBid, msg.MinimumBid, msg.HighestProxyBid);
callback(BidDate);
});
}
var tester = GetAllBidData(function(yourValue){
//do stuff here with yourValue
});