How can Ajax do asynchronous request and response

2019-08-09 07:10发布

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.

4条回答
太酷不给撩
2楼-- · 2019-08-09 07:49

How can Ajax do asynchronous request and return a synchronous result

You can't. It's just impossible. If your code really tries to do that, it will fail.

查看更多
Lonely孤独者°
3楼-- · 2019-08-09 07:55

Since ajax is asynchronous, return AjaxResult is actually executed before the ajax result completes. You can not return in this way; you need to perform some action in the callback of the ajax requests or use deferred.

查看更多
The star\"
4楼-- · 2019-08-09 08:14

Ajax is asynchronous call to your method and it do the processing in the back for server trip. You will not get the result until the success method is called. You can read more about jquery ajax here

You can set async attribute to false of ajax() to make a synchronous call.

EDIT: Using deferreds --

$.Deferred can be used to run code after some other code has completed. Ajax is an excellent example, and all of the jQuery ajax methods (except .load) implement the $.Deferred interface. You can use $.when to watch deferreds. For example:

login = function () {
   return $.ajax({...

The deferred gets returned from the method above, so you can do the following:

$.when(login()).done(function (response) { ... });

Any code that needs to be synchronized with the ajax response has to go in the .done callback.

Note that this is not much different than just using the success callback with $.ajax. The point is that all of your work that relies on what is returned from Ajax needs to be done in these callbacks.

查看更多
闹够了就滚
5楼-- · 2019-08-09 08:16

It has to do with the fact that AJAX is asynchronous (that's actually the meaning of the first A in it). alert stops the code until you press the button, and the request has time to complete. With no alert, 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.

查看更多
登录 后发表回答