简体   繁体   English

将参数从函数传递到其回调

[英]Passing parameters from function to its callback

Here's my code: 这是我的代码:

First the execution of the program comes here: 首先执行程序在这里:

refreshTree(function() {
            $.ajax({
                type: "POST",
                url: "/ControllerName/MethodName1",
                success: function (data) {
                    refresh();
                }
            });
        });

Here's the definition of refreshTree() : 这是refreshTree()的定义:

function refreshTree(callback) {
    var isOk = true;
    $.ajax({
        type: "GET",
        url: "/ControllerName/MethodName2",
        success: function(data) {
            if (data == 'True') {
                isOk = false;
            }
            callback();
        }
    });
}

And here's the refresh() method: 这是refresh()方法:

function refresh() {
    if (isOk) {
        //do something
    }
}

The problem is, I don't know how to get the isOk variable in refresh() . 问题是,我不知道如何在refresh()获取isOk变量。 Is there some way to send the variable to refresh() , without it being a global variable? 有没有某种方法可以将变量发送到refresh()而不将其作为全局变量?

You capture it in a closure here: 您可以在此处将其捕获为闭包:

refreshTree(function(isOk) {
    $.ajax({
        type: "POST",
        url: "/ControllerName/MethodName1",
        success: function (data) {
            refresh(isOk);
        }
    });
});

And pass it in here: 并在这里传递:

function refreshTree(callback) {
    var isOk = true;
    $.ajax({
        type: "GET",
        url: "/ControllerName/MethodName2",
        success: function(data) {
            if (data == 'True') {
                isOk = false;
            }
            callback(isOk);
        }
    });
}

and here: 和这里:

function refresh(isOk) {
    if (isOk) {
        //do something
    }
}

Simply Pass it as parameter: 只需将其作为参数传递:

refreshTree(function(status) {
        $.ajax({
            type: "POST",
            url: "/ControllerName/MethodName1",
            success: function (data) {
                refresh(status);
            }
        });
    });

refreshTree() function: refreshTree()函数:

function refreshTree(callback) {
var isOk = true;
$.ajax({
    type: "GET",
    url: "/ControllerName/MethodName2",
    success: function(data) {
    var isOk=true;
        if (data == 'True') {
            isOk = false;
        }
        callback(isOk);
    }
});

} }

Refresh() method: Refresh()方法:

function refresh(status) {
if (status) {
    //do something
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM