Javascript 传递包含参数的回调函数?

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

Passing a callback function with included parameters?

javascriptjqueryajaxcallback

提问by Brett

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);
        }
    });    

}

Edit: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();    

}

Now if I wanted to pass the grading_companyvariable to the callback function as a parameter is there a way to do that without having to add it as another parameter in the runAjaxcall? I'm trying to keep the runAjaxfunction 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.

现在,如果我想将grading_company变量作为参数传递给回调函数,有没有办法做到这一点,而不必在runAjax调用中将其添加为另一个参数?我试图保持该runAjax函数对其他用途开放,所以我不想传递任何额外的参数;但如果它可以以某种方式包含在回调中,那就太好了。

回答by jbabey

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.

这允许您将参数传递给内部函数。

Edit: to allow for the ajax response:

编辑:允许 ajax 响应:

// Set the callback function to run on success
var callback = function (response) {
    showGradesBox(grading_company, response);
};

回答by jwatts1980

Another possibility is instead of doing dataStringdo dataObjectthen pass that object to the callback. Like so:

另一种可能性是不做dataStringdodataObject然后将该对象传递给回调。像这样:

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 object
        var dataObject = {
            'gc_id' : grading_company
            /*to do multiples..
            'item1' : value1, 
            'item2' : value2, 
            'etc' : etc */
        }

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

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

    }

}

function runAjax(loadUrl, dataObject, callback) {

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

}

Note the addition of $.param().

注意添加$.param().

Then in the callback function, you should know what data you're after. If function setGrades(resp, data) { ... }was the callback, then you can access the values in setGrades

然后在回调函数中,你应该知道你要的是什么数据。如果function setGrades(resp, data) { ... }是回调,那么您可以访问中的值setGrades

function setGrades(resp, data) {
   alert( data.gc_id);
}

EDIT

编辑

After testing, I realize that $(dataObject).serialize()will not work. So I've updated to use $.param(). Please see this SO postfor more info.

经过测试,我意识到这$(dataObject).serialize()行不通。所以我已经更新为使用$.param(). 请参阅此 SO 帖子以获取更多信息。