Javascript 将回调函数传递给 jQuery AJAX 成功函数

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

Passing a callback function to jQuery AJAX success function

javascriptjqueryajaxcallback

提问by Brett

I'm trying to pass in a function to run when the AJAX call is successful, however it's not working as it say's that "callback is not a function".

我试图传入一个函数以在 AJAX 调用成功时运行,但是它不起作用,因为它说“回调不是函数”。

Example:

例子:

Calling Code:

调用代码:

getGrades(var);    

JS:

JS:

function getGrades(grading_company) {

    // Set file to get results from..
    var loadUrl = "ajax_files/get_grades.php";

    // Set data string
    var dataString = 'gc_id=' + grading_company;

    // Set the callback function to run on success
    var callback = 'showGradesBox';

    // Run the AJAX request
    runAjax(loadUrl, dataString, callback);

}

function showGradesBox(response) {

    // Code here...

}

function runAjax(loadUrl, dataString, callback) {

    jQuery.ajax({
        type: 'GET',
        url: loadUrl,
        data: dataString,
        dataType: 'html',
        error: ajaxError,
        success: function(response) {
            callback(response);
        }
    });    

}

Now if I replace this line below with the function name itself it works:

现在,如果我用函数名称本身替换下面的这一行,它会起作用:

callback(response);

But I can't get it to work like above where I get the function name from a passed in parameter.

但是我不能像上面那样工作,我从传入的参数中获取函数名称。

回答by micha

showGradesBoxis a string in your code. So you have two options to execute the callback function:

showGradesBox是代码中的字符串。所以你有两个选项来执行回调函数:

If you want to keep the string you can use

如果你想保留你可以使用的字符串

this[callback](response);

(if callbackis defined in global scope you can also use window[callback](response);

(如果callback在全局范围内定义,您也可以使用window[callback](response);

Or you can pass the function directly:

或者你可以直接传递函数:

var callback = showGradesBox;

(in this case you can keep your existing code for callback execution)

(在这种情况下,您可以保留现有代码用于回调执行)