可重用的jQuery Ajax请求 [英] Reusable jquery ajax requests

查看:67
本文介绍了可重用的jQuery Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net mvc开发一个Web应用程序...我正在通过使用jquery的ajax请求列出客户端,工作人员,报表的详细信息...我正在做的是编写单独的函数(jquery ajax请求)对于每个动作(即)视图,添加,编辑,删除...

I am developing a web application using asp.net mvc... I am listing out the details of Clients,Staff,Reports via ajax requests using jquery... What i am doing is writing seperate functions(jquery ajax requests) for each actions (ie) view,add,edit,Delete ...

//Clients
function getClients(currentPage) {
    $.ajax({
        url: "Clients/GetClients",
        data: { 'currentPage': (currentPage + 1), 'pageSize': 5 },
        contentType: "application/json; charset=utf-8",
        global: false,
        async: false,
        dataType: "json",
        beforeSend: function() { $('.loading').show(); },
        complete: function() { $('.loading').hide(); },

        success: function(data) {
            if (data.isRedirect && data.isRedirect === true) {
                alert('must redirect to ' + data.redirectUrl);
                location = 'http://www.google.com';
            }
            else {
                var divs = '';
                $("#hfId").val('');
                $("#ResultsDiv").empty();
                $.each(data.Results, function() {
                    divs += '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + this.ClientName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + this.ClientMobNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + this.ClientId + ' onclick="storeIds();"/></span><br/><br/><span class="resultfields">Address&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + this.ClientAddress + '</span></div>';
                });
                $("#ResultsDiv").append(divs);
                $(".resultsdiv:even").addClass("resultseven");
                $(".resultsdiv").hover(function() {
                    $(this).addClass("resultshover");
                }, function() {
                    $(this).removeClass("resultshover");
                });
                $("#HfId").val("");
                $("#HfId").val(data.Count);

            }
        }
    });
    return false;
}

//Drivers
function getDrivers(currentPage) {

    $.ajax({
         url: "Staff/GetDrivers",
        data: { 'currentPage': (currentPage + 1), 'pageSize': 5 },
        contentType: "application/json; charset=utf-8",
        global: false,
        async: false,
        dataType: "json",
        beforeSend: function() { $('.loading').show(); },
        complete: function() { $('.loading').hide(); },

        success: function(data) {
            if (data.isRedirect && data.isRedirect === true) {
                alert('must redirect to ' + data.redirectUrl);
                location = 'http://www.google.com';
            }
            else {
                var divs = '';
                $("#hfId").val('');
                $("#ResultsDiv").empty();
                $.each(data.Results, function() {
                divs += '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + this.DriverName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + this.DriverMobileNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + this.DriverId + ' onclick="storeIds();"/></span></div>';
                });
                $("#ResultsDiv").append(divs);
                $(".resultsdiv:even").addClass("resultseven");
                $(".resultsdiv").hover(function() {
                    $(this).addClass("resultshover");
                }, function() {
                    $(this).removeClass("resultshover");
                });
                $("#HfId").val("");
                $("#HfId").val(data.Count);

            }
        }
    });
    return false;
}

//get client by id
function getClientbyId(clientId) {
    $.ajax({
        url: "Clients/getClientById",
        data: { 'clientId': clientId },
        contentType: "application/json; charset=utf-8",
        global: false,
        async: false,
        dataType: "json",
        beforeSend: function() { $('.loading').show(); },
        complete: function() { $('.loading').hide(); },
        success: function(data) {
            $("#Name").val(data.ClientName);
            $("#MobileNo").val(data.ClientMobNo);
            $("#Address").val(data.ClientAddress);
            $("#hfEditId").val(data.ClientId);
            $("#adddiv").show();
            $("#ResultsDiv").hide();
            $("#PagerDown").hide();
            $("#ImageButtonDiv").hide();
        }
    });
    return false;
}

//get driver by id
function getDriverById(driverId) {
    $.ajax({
         url: "Staff/getDriverById",
        data: { 'driverId': driverId },
        contentType: "application/json; charset=utf-8",
        global: false,
        async: false,
        dataType: "json",
        beforeSend: function() { $('.loading').show(); },
        complete: function() { $('.loading').hide(); },
        success: function(data) {
            $("#Name").val(data.DriverName);
            $("#MobileNo").val(data.DriverMobileNo);
            $("#hfEditId").val(data.DriverId);
            $("#adddiv").show();
            $("#ResultsDiv").hide();
            $("#PagerDown").hide();
            $("#ImageButtonDiv").hide();
        }
    });
    return false;
}


//clients delete
function deleteClients(clientIds) {
    $.ajax({
        url: "Clients/deleteClients",
        data: { 'ids': clientIds },
        contentType: "application/json; charset=utf-8",
        global: false,
        async: false,
        dataType: "json",
        beforeSend: function() { $('.loading').show(); },
        complete: function() { $('.loading').hide(); },
        success: function(data) {
        if (data.Result == "Success") {
            getClients(0);
            var maxvalues = $("#HfId").val();
            $(".pager").pagination(maxvalues, {
                callback: getClients,
                current_page: 0,
                items_per_page: 5,
                num_display_entries: 5,
                next_text: 'Next',
                prev_text: 'Prev',
                num_edge_entries: 1
            });
            return false;
            }
        }
    });
    $("#alert").remove();
    topBar('successfully deleted');
    return false;
}

//delete drivers
function deleteDrivers(driverIds) {
    $.ajax({
    url: "Staff/deleteDrivers",
        data: { 'ids': driverIds },
        contentType: "application/json; charset=utf-8",
        global: false,
        async: false,
        dataType: "json",
        beforeSend: function() { $('.loading').show(); },
        complete: function() { $('.loading').hide(); },
        success: function(data) {
            if (data.Result == "Success") {
                getDrivers(0);
                var maxvalues = $("#HfId").val();
                $(".pager").pagination(maxvalues, {
                callback: getDrivers,
                    current_page: 0,
                    items_per_page: 5,
                    num_display_entries: 5,
                    next_text: 'Next',
                    prev_text: 'Prev',
                    num_edge_entries: 1
                });
                return false;
            }
        }
    });
    $("#alert").remove();
    topBar('successfully deleted');
    return false;
}

如何将这些函数变成单个函数,然后将值传递给该函数...有没有办法做到这一点...

How to make these functions into a single function and just pass the values to the function... Is there way to do this...

推荐答案

由于所有函数都具有相似的AJAX设置选项,因此我建议您使用

As all your functions have similar AJAX setup options I would recommend you to setup common options globally using the $.ajaxSetup function:

$(function() {
    $.ajaxSetup({
        contentType: 'application/json; charset=utf-8',
        global: false,
        async: false,
        dataType: 'json',
        beforeSend: function() { $('.loading').show(); },
        complete: function() { $('.loading').hide(); },
    });
});

接下来让我们首先考虑getClientsgetDrivers函数.那些看起来差不多.我只能看到它们之间的唯一区别是您发送AJAX请求的url和要附加到#ResultsDiv的html.因此,您可以有两个单独的函数来处理结果:

Next let's first consider the getClients and getDrivers functions. Those look pretty much the same. The only difference I can see between them is the url you are sending the AJAX request and the html that's being appended to the #ResultsDiv. So you could have two separate functions that handle the result:

function formatDriversResult(result) {
    return '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + result.DriverName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + result.DriverMobileNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + result.DriverId + ' onclick="storeIds();"/></span></div>';
}

function formatClientsResult(result) {
    return '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + result.ClientName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + result.ClientMobNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + result.ClientId + ' onclick="storeIds();"/></span><br/><br/><span class="resultfields">Address&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + result.ClientAddress + '</span></div>';
}

最后,这两个功能可以合并为一个功能:

And finally the two functions could be merged into a single one:

function getEntities(url, currentPage, formatResultFunction) {
    $.ajax({
        url: url,
        data: { 'currentPage': (currentPage + 1), 'pageSize': 5 },
        success: function(data) {
            if (data.isRedirect && data.isRedirect === true) {
                alert('must redirect to ' + data.redirectUrl);
                location = 'http://www.google.com';
            }
            else {
                var divs = '';
                $("#hfId").val('');
                $("#ResultsDiv").empty();
                $.each(data.Results, function() {
                    divs += formatResultFunction(this);
                });
                $("#ResultsDiv").append(divs);
                $(".resultsdiv:even").addClass("resultseven");
                $(".resultsdiv").hover(function() {
                    $(this).addClass("resultshover");
                }, function() {
                    $(this).removeClass("resultshover");
                });
                $("#HfId").val("");
                $("#HfId").val(data.Count);

            }
        }
    });
    return false;
}

现在,当您想获得当前客户时:

Now when you want to get the current clients:

var clients = getEntities("Clients/GetClients", currentPage, formatClientsResult);

以及要获取当前驱动程序的时间:

and when you want to get the current drivers:

var drivers = getEntities("Staff/GetDrivers", currentPage, formatDriversResult);


接下来,让我们考虑getClientbyIdgetDriverById函数.它们可以简化为:


Next let's consider the getClientbyId and getDriverById functions. They could be simplified to:

function getEntityById(data, url, formatResultFunction) {
    $.ajax({
        url: url,
        data: data,
        success: function(data) {
            formatResultFunction(data);
            $("#adddiv").show();
            $("#ResultsDiv").hide();
            $("#PagerDown").hide();
            $("#ImageButtonDiv").hide();
        }
    });
    return false;
}

其余的可以使用相同的模式.

The same pattern could be used for the rest.

这篇关于可重用的jQuery Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆