Bre*_*ett 24 javascript ajax jquery callback
我有以下代码..
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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
编辑:这是作为回调函数调用的函数:
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();
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我想将grading_company变量传递给回调函数作为参数有没有办法做到这一点,而不必将其作为另一个参数添加到runAjax调用中?我试图保持该runAjax功能对其他用途开放,所以我不想传递任何额外的参数; 但如果它可以某种方式包含在回调中那么好.
jba*_*bey 46
将回调更改为匿名函数:
// Set the callback function to run on success
var callback = function () {
showGradesBox(grading_company);
};
Run Code Online (Sandbox Code Playgroud)
这允许您将参数传递给内部函数.
编辑:允许ajax响应:
// Set the callback function to run on success
var callback = function (response) {
showGradesBox(grading_company, response);
};
Run Code Online (Sandbox Code Playgroud)