将回调函数传递给jQuery AJAX成功函数 [英] Passing a callback function to jQuery AJAX success function
问题描述
我正在尝试传递一个函数以在AJAX调用成功时运行,但是它不能正常工作,因为它说回调不是函数".
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".
示例:
呼叫代码:
getGrades(var);
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.
推荐答案
showGradesBox
是代码中的字符串.因此,您有两个选项可以执行回调函数:
showGradesBox
is a string in your code. So you have two options to execute the callback function:
如果要保留字符串,可以使用
If you want to keep the string you can use
this[callback](response);
(如果callback
是在全局范围内定义的,则也可以使用window[callback](response);
(if callback
is defined in global scope you can also use 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)
这篇关于将回调函数传递给jQuery AJAX成功函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!