【问题标题】:One ajax for multiple function names一个 ajax 用于多个函数名称
【发布时间】:2015-08-07 02:38:37
【问题描述】:

我有运行相同 jquery 的 ShowExpired()SessionDestroy() 函数。 唯一的区别:我在 ShowExpired() 中有 if 语句。

我们如何缩小它?

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

}

【问题讨论】:

  • 如果两个函数都做同样的事情,那你为什么需要检查if?因为 ajax 部分没有像urldata 等那样发生变化。那么为什么你需要if 声明呢?

标签: jquery ajax


【解决方案1】:

为了确定,我不得不在 diffchecker 中运行它。 :Dhttps://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

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

【讨论】:

    猜你喜欢
    • 2022-08-22
    • 2019-06-20
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多