One ajax for multiple function names

时间:2015-08-07 02:38:37

标签: jquery ajax

I have ShowExpired() and SessionDestroy() functions running the same jquery. Only difference: I have if statement in ShowExpired().

How can we shrink it?

function ShowExpired() {
    if (isextend == false) {
        $.ajax({
            type: "POST",
            cache: false,
            url: "../../html/frmLogout.aspx/Sessionlogout",
            data: "{userid:" + userid + "}",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            async: false,
            success: function (data, e, jqxhr) {
                if (data.d.result) {
                    window.location.href = '../HTML/frmLogin.aspx';
                }
            },
            error: function (data, e, jqxhr) { alert("logout ERROR=" + data.responseText); }
        });
    }

}


function SessionDestroy() {

        $.ajax({
            type: "POST",
            cache: false,
            url: "../../html/frmLogout.aspx/Sessionlogout",
            data: "{userid:" + userid + "}",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            async: false,
            success: function (data, e, jqxhr) {
                if (data.d.result) {
                    window.location.href = '../HTML/frmLogin.aspx';
                }
            },
            error: function (data, e, jqxhr) { alert("logout ERROR=" + data.responseText); }
        });

}

1 个答案:

答案 0 :(得分:0)

我必须在diffchecker中运行它才能确保。 :D https://www.diffchecker.com/jcknyfg4

在这种情况下,您的第一个功能可能会缩小为:

function ShowExpired() {
    if (isextend == false) {
        SessionDestroy();
    }
}

在您的示例中,这很容易。 在一般情况下,有很多选项可以使ajax调用更具可读性并占用更少的代码空间。谷歌吧!

一些指示:

https://github.com/yaymukund/jquery-ajax-wrap

https://lostechies.com/derickbailey/2012/05/04/wrapping-ajax-in-a-thin-command-framework-for-backbone-apps/

Wrap jQuery's $.ajax() method to define global error handling

当然,编写自己的包装器也是一种选择。它的复杂性不高。