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

时间:2021-12-17 09:38:49

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.

但我无法让它像上面那样从传入的参数中获取函数名称。

1 个解决方案

#1


14  

showGradesBox is 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 callback is defined in global scope you can also use window[callback](response);

(如果回调是在全局范围内定义的,你也可以使用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)

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

#1


14  

showGradesBox is 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 callback is defined in global scope you can also use window[callback](response);

(如果回调是在全局范围内定义的,你也可以使用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)

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