I find a fantastic bug when I use jQuery ajax to do a request to web service:
var AjaxResult;
login = function () {
AjaxResult = "";
$.ajax({
type: "POST",
url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlannerWebService.asmx/AuthenticateLogin",
data: { username: this.username, password: this.password },
dataType: 'jsonp',
success: function (response) {
//the response value is 'success'
AjaxResult = response;
},
error: function (data, status, e) {
alert("error:" + e);
}
});
//alert(AjaxResult);
//if i do not alert a message here, this function will return a null value
//however, i do alert here, then i get a 'success' value.
return AjaxResult;
}
How could this happen.
I am confused as to why the AjaxResult returns its value before the ajax method set response value to it.
It has to do with the fact that AJAX is asynchronous (that’s actually the meaning of the first A in it).
alertstops the code until you press the button, and the request has time to complete. With noalert, the function proceeds immediately, the AJAX has barely begun its work, and of course the value is still empty.Generally, you can’t have functions return values that they get from AJAX. Set up a callback for it, and deal with it when it comes.