传递一个回调函数,包括参数? [英] Passing a callback function with included parameters?
问题描述
我有以下code这个..
I have this below code..
function getGrades(grading_company) {
if (grading_company == 'Not Specified') {
// Remove grades box & show condition box
showConditionBox();
} else {
// 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 runAjax(loadUrl, dataString, callback) {
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: dataString,
dataType: 'html',
error: ajaxError,
success: function(response) {
callback(response);
}
});
}
编辑:这是被称为回调函数的函数:
Here is the function that gets called as the callback function:
function showGradesBox(response) {
// Load data into grade field
jQuery('#grade').html(response);
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
现在,如果我想在 grading_company
变量传递给回调函数的参数是有办法做到这一点,而无需将其添加为另一个参数中的 runAjax
打电话?我试图保持 runAjax
功能开放给其他用途,所以我不希望传递任何额外的参数;但如果能以某种方式被包含在回调中那么大。
Now if I wanted to pass the grading_company
variable to the callback function as a parameter is there a way to do that without having to add it as another parameter in the runAjax
call? I'm trying to keep the runAjax
function open to other usage so I don't want to pass in any extra parameters; but if it can somehow be included within the callback then great.
推荐答案
改变你的回调一个匿名函数:
change your callback to an anonymous function:
// Set the callback function to run on success
var callback = function () {
showGradesBox(grading_company);
};
这可让您将参数传递给内部函数。
This allows you to pass parameters to the inner function.
编辑:允许Ajax响应:
to allow for the ajax response:
// Set the callback function to run on success
var callback = function (response) {
showGradesBox(grading_company, response);
};
这篇关于传递一个回调函数,包括参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!