JavaScript传递函数参数和返回值

JavaScript Pass Function Argument Out Along With Return Value

本文关键字:返回值 参数 传递函数 JavaScript      更新时间:2023-09-26

如何在Java Script中传递ajax get的函数参数以及返回值?

在下面的示例中,我想通过GetServer函数参数id的值,并使其可访问函数returnValue

function getServerList(id) {
        $.ajax({
            type: "GET",
            url: "/BackEndFunction/" + id,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: returnValue
        });
}
function returnValue(Data) {
    var _size = 0;
    var id= id // passed from getserverlist
    for (var i = 0; i< Data.length; i++) {
        _size += Data[i]._size;
    }
    data_dictionary[id] = _size;
}

匿名函数的救援

function getServerList(id) {
    $.ajax({
        type: "GET",
        url: "/BackEndFunction/" + id,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            returnValue(data, id);
        }
    });
}

你也可以代理它

function getServerList(id) {
    $.ajax({
        type: "GET",
        url: "/BackEndFunction/" + id,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: $.proxy(returnValue, this, id)
    });
}