0
我一直在努力尋找最後一整晚找到錯誤,但找不到。我的JavaScript代碼不能正常工作。JavaScript不按邏輯工作
var currCab = 0;
var cabBooked = 0;
function sendMessage(cabId)
{
if(cabBooked == 1) {
return;
}
// get data from html page
$.post("sendMessage.php",data,
function(data,status){
$("#status").html(data);
});
}
function checkBookingStatus()
{
var data = "bookingId="+$("#bookingId").val();
$.post("checkBookingStatus.php",data,
function(data,status){
// callback here
var ans = data.indexOf("true");
if(ans!= -1) {
console.log("returning true from checkBookingStatus");
$("#simpleStatus").html("Cab booked. You can close tab now");
cabBooked = 1;
return true;
} else {
console.log("returning false from checkBookingStatus");
return false;
}
});
}
function tryCabAlloc()
{
if(!checkBookingStatus()) {
if(cabBooked == 1) {
return;
}
var checkid = document.getElementById("cabId"+currCab);
if(checkid==null) {
$("#simpleStatus").html("Cab could not be booked.");
$("#status").html("No more clients to communicate with.");
} else {
var cid = $("#cabId"+currCab).val();
sendMessage(cid);
updateTrying(cid);
currCab = currCab + 1;
}
}
}
$(document).ready(function() {
$("#simpleStatus").html("Please wait. The communication is being started...");
$("#status").html("GCM push initiating ...");
tryCabAlloc();
setInterval(function(){
if(cabBooked==0) {
tryCabAlloc();
} else {
throw '';
}
},95000);
});
的代碼應該停止時,checkBookingStatus返回true,cabBooked設置爲1,但不停止所有工作。我不知道爲什麼。
AJAX是異步的。從回調函數返回不會從'checkBookingStatus()'返回,因爲它已經在發送AJAX請求時返回。 – Barmar
如何克服這一點? – Divanshu
按照重複問題中的解釋,在回調函數中執行您想要執行的操作。 – Barmar