How can Ajax do asynchronous request and response a synchronous result

强颜欢笑 提交于 2019-12-11 04:48:50

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/13966223/how-can-ajax-do-asynchronous-request-and-response-a-synchronous-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!