等待来自调用函数的 jquery ajax 回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11576176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:44:44  来源:igfitidea点击:

wait for a jquery ajax callback from calling function

jqueryajaxcallback

提问by art vanderlay

I have reviewed a lot of answers to this type of question and now I am confused as to the best way. Given the latest jquery, I am wanting to

我已经查看了很多此类问题的答案,现在我对最佳方法感到困惑。鉴于最新的jquery,我想要

  1. Call an ajax function
  2. do ajax processing (success or error) // works fine
  3. on success or error return the status to the calling function for further processing
  1. 调用ajax函数
  2. 做ajax处理(成功或错误)//工作正常
  3. 成功或错误时将状态返回给调用函数以进行进一步处理

in the calling function (doAjax), how do I wait for a callback then complete the processing for success or error (in this case its on success clear a form, on error keep it as is)

在调用函数(doAjax)中,我如何等待回调然后完成成功或错误的处理(在这种情况下,成功时清除表单,错误时保持原样)

Thx for any advice,

感谢任何建议,

Art [EDIT]There was a typo as you guys spotted, call should have been doAnAjax not doAjax

艺术 [编辑]你们发现有一个错字,调用应该是 doAnAjax 而不是 doAjax

$(function () {
    doAnAjax(Url, data, function (myRtn) {
        if (myRtn == "success") {
            resetForm($('#myForm'));
            resetForm($('form[name=addChlGrp]'));
        } else {
            $('.rtnMsg').html("Opps! Ajax Error");
        }
    });
});

function doAnAjax(newUrl, data) {
    $.ajax({
        url: newUrl,
        async: true,
        dataType: 'html',
        beforeSend: function () {
            $('.rtnMsg').html("<img src=_cssStyleImg_-A-loading.gif>");
        },
        type: "GET",
        data: data,
        cache: false,
        success: function (data, textStatus, xhr) {
            $('.rtnMsg').html(data);
            myRtnA = "Success"
            return myRtnA;
        },
        error: function (xhr, textStatus, errorThrown) {
            $('.rtnMsg').html("opps: " + textStatus + " : " + errorThrown);
            myRtnA = "Error"
            return myRtnA;
        }
    });
}

采纳答案by thecodeparadox

You've got to use a callback function. Try this below:

你必须使用回调函数。试试这个:

$(function() {

   // I think doAjax should doAnAjax()
   // here you're passing callback
   // but you're not using it doAnAjax()

    doAnAjax(Url, data, function(myRtn) {
        if (myRtnV == "success") {
            resetForm($('#myForm'));
            resetForm($('form[name=addChlGrp]'));
        } else {
            $('.rtnMsg').html("Opps! Ajax Error");
        }
    });
});

// pass callback as third parameter to doAnAjax()

function doAnAjax(newUrl, data, callBack) {
    $.ajax({
        url: newUrl,
        async: true,
        dataType: 'html',
        beforeSend: function() {
            $('.rtnMsg').html("<img src=_cssStyleImg_-A-loading.gif>");
        },
        type: "GET",
        data: data,
        cache: false,
        success: function(data, textStatus, xhr) {
            $('.rtnMsg').html(data);
            myRtnA = "Success"
            return callBack( myRtnA );  // return callBack() with myRtna
        },
        error: function(xhr, textStatus, errorThrown) {
            $('.rtnMsg').html("opps: " + textStatus + " : " + errorThrown);
            myRtnA = "Error"
            return callBack ( myRtnA ); // return callBack() with myRtna
        }
    });

回答by Gavin

As previously mentioned, using Callbacks.

如前所述,使用回调。

function process(url, params, successCallback, errorCallback) {
    $.ajax({
        success : successCallback,
        error : errorCallback,
        data : params,
        url : url,
        type : 'POST',
        dataType : 'json'
    });
}

process(
    'http://www.google.co.uk', 
    { 
        param1 : 'a' 
    }, 
    function(resp) { 
        alert('Success');
    },
    function() {
        alert('Uh oh');
    }
);

You can then pass any function to processand it will be called on success/error.

然后您可以将任何函数传递给process它,它会在成功/错误时被调用。

回答by Jon Taylor

The answer is you don't, but it is easily achievable. The idea of AJAX is it is asynchronous, hence the AJAX. This means that the function that originally calls your ajax will not wait for it to complete and instead all work to be completed after an ajax call should be in the success or error handlers.

答案是你没有,但它很容易实现。AJAX 的思想是它是异步的,因此是AJAX。这意味着最初调用 ajax 的函数不会等待它完成,而是在 ajax 调用后完成的所有工作都应该在成功或错误处理程序中。

If you need something to be synchronous you can change your flag from async:trueto async:falsebut then it becomes really a SJAX call (not even sure the term exists but, technically it isnt an AJAX call anymore).

如果您需要同步某些东西,您可以将标志从 更改为async:trueasync:false但它实际上变成了 SJAX 调用(甚至不确定该术语是否存在,但从技术上讲,它不再是 AJAX 调用)。

回答by Chase Saunders

Check out 'derferred' in jquery. The below example uses deferred.done with async turned off, and seems to work for me.!

在 jquery 中查看“延迟”。下面的示例使用 deferred.done 并关闭异步,似乎对我有用。!

$.ajax({
    url: "http://www.whatever.com/whatever",
    async: false }).done(function( data ) {
        alert(data); //or whatever
    })