我编写了一个自定义 js 模块,它基本上发送消息并且需要等待响应才能继续:
var manageBooking = (function (jQ) {
//decalre private variables
var domain, msgRecieved, msgResponse, validationValue;
//decalre private functions
var sendMessage, wait;
// A private variables
domain = document.domain;
msgRecieved = false;
msgResponse = null;
wait = function(timeOutStep){
var w;
console.log('msgRecieved', msgRecieved);
if (msgRecieved === true) {
clearTimeout(w);
return;
} else {
console.log('waiting..');
w = setTimeout(wait, timeOutStep, timeOutStep);
}
}
// A private function to send messages
sendMessage = function( requestURL, data, type ) {
console.log(requestURL);
console.log(data);
console.log(type);
//reset vars to defaults
msgRecieved = false;
msgResponse = null;
jQuery.ajax({
url: "http://"+domain+"/_ajax/"+requestURL,
dataType: "html",
async: true,
data: data,
type: type,
success: function(msg){
console.log(msg);
msgResponse = msg;
msgRecieved = true;
}
});
console.log('after ajax call');
wait(500);
console.log('after wait');
console.log('msgRecieved', msgRecieved);
return;
};
return {
// A public variable
errorMsg: "",
validationName: "",
bookingID: "",
output: "",
// A public function to login
login: function( enteredBookingID, enteredSurname ) {
// Call private sendMsg
sendMessage("user_login/"+enteredBookingID+"/"+enteredSurname, null, 'GET');
console.log(msgResponse);
throw "error";
//check response
var patt=/Sorry/i;
//test pattern
var result=patt.test($.trim(msgResponse));
//if false OK
if (result === false) {
var split = msgResponse.split('|');
validationName = split[0];
validationValue = split[1];
bookingID = enteredBookingID
return true;
}
//else error
errorMsg = msgResponse;
return false;
}
};
})(jQuery);
manageBooking.login(123,123);
我遇到的问题是强制sendMessage
函数等到 ajax 完成并设置msgRecieved
为 true。
但是,该函数似乎sendMessage
命中该wait
函数一次,然后继续。以下控制台输出显示了事件的顺序:
GET http://website/_ajax/user_login/123/123
after ajax call //sendMessage()
msgRecieved, false //wait()
waiting.. //wait()
after wait //sendMessage()
msgRecieved, false //sendMessage()
null//login()
uncaught exception: error //login()
<p>Sorry, we cannot locate your details. </p> <!-- jQuery Ajax call -->
msgRecieved, true //wait()
我感到困惑的是,该wait
功能似乎在最后再次触发..
谁能给我一些关于让它工作的指示?