Javascript 带有ajax的Javascript回调函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4988277/
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-23 15:06:15  来源:igfitidea点击:

Javascript callback functions with ajax

javascriptjqueryajaxcallback

提问by Zak Henry

I am writing a generic function that will be reused in multiple places in my script.

我正在编写一个通用函数,它将在我的脚本中的多个位置重复使用。

The function uses ajax (using jQuery library) so I want to somehow pass in a function (or lines of code) into this function to execute when ajax is complete. I believe this needs to be a callback function, but after reading through a few callback answers I'm still a bit confused about how I would implement in my case.

该函数使用 ajax(使用 jQuery 库),所以我想以某种方式将函数(或代码行)传入该函数以在 ajax 完成时执行。我相信这需要是一个回调函数,但是在阅读了一些回调答案之后,我仍然对如何在我的情况下实现感到有些困惑。

My current function is:

我目前的功能是:

function getNewENumber(parentENumber){

        $.ajax({
               type: "POST",
               url: "get_new_e_number.php",
               data: {project_number: projectNumber, parent_number: parentENumber},
               success: function(returnValue){
                    console.log(returnValue);
                    return returnValue; //with return value excecute code

                },
                error: function(request,error) {
                    alert('An error occurred attempting to get new e-number');
                    // console.log(request, error);
                }
        });
    }

With this function I want to be able to do something in the same way other jQuery functions work ie;

有了这个函数,我希望能够以与其他 jQuery 函数相同的方式做一些事情,即;

var parentENumber = E1-3;

getNewENumber(parentENumber, function(){
    alert(//the number that is returned by getNewENumber);
});

采纳答案by user113716

Just give getNewENumberanother parameter for the function, then use that as the callback.

只需getNewENumber为该函数提供另一个参数,然后将其用作回调。

   // receive a function -----------------v
function getNewENumber( parentENumber, cb_func ){

    $.ajax({
           type: "POST",
           url: "get_new_e_number.php",
           data: {project_number: projectNumber, parent_number: parentENumber},

             // ------v-------use it as the callback function
           success: cb_func,
            error: function(request,error) {
                alert('An error occurred attempting to get new e-number');
                // console.log(request, error);
            }
    });
}

var parentENumber = E1-3;

getNewENumber(parentENumber, function( returnValue ){
    alert( returnValue );
});

回答by Mariano Desanze

@patrick dw's anwseris correct. But if you want to keep calling the console.log(or any other actions) always, no matter what the caller code function does, then you can add the callback (your new parameter) inside the success function you already have:

@patrick dw 的回答是正确的。但是如果你想一直调用console.log(或任何其他操作),无论调用者代码函数做什么,那么你可以在你已经拥有的成功函数中添加回调(你的新参数):

function getNewENumber(parentENumber, cb_func /* <--new param is here*/){ 

    $.ajax({
           type: "POST",
           url: "get_new_e_number.php",
           data: {project_number: projectNumber, parent_number: parentENumber},
           success: function(returnValue){
                console.log(returnValue);
                cb_func(returnValue); // cb_func is called when returnValue is ready.
            },
            error: function(request,error) {
                alert('An error occurred attempting to get new e-number');
                // console.log(request, error);
            }
    });
}

And the calling code remains the same as yours except that the function will receive the returnValue by parameter:

并且调用代码与您的代码保持相同,只是该函数将通过参数接收 returnValue:

var parentENumber = E1-3;

getNewENumber(parentENumber, function(val /* <--new param is here*/){
    alert(val);
});

回答by Alnitak

This would be better done with jQuery's Deferred Objects. Have your AJAX call returnthe jqXHRobject.

使用 jQuery 的Deferred Objects可以更好地做到这一点。让你的AJAX调用返回jqXHR对象。

function getNewENumber(parentENumber) {
    return $.ajax( { ... } );
}

getNewENumber(E1 - 3).then(success_callback, error_callback);

If you want to keep the error callback withinthat function you can register that there instead:

如果您想该函数中保留错误回调,您可以在那里注册:

function getNewENumber(parentENumber) {
    var jqXHR = $.ajax( { ... } );
    jqXHR.fail( ... );
    return jqXHR;
}

getNewENumber(E1 - 3).done(success_callback);