如何优化(最小化)jQuery的AJAX调用 [英] How to optimize (minimize) jQuery AJAX calls

查看:105
本文介绍了如何优化(最小化)jQuery的AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有超过50 AJAX从我的code不同的功能要求。所有这些调用有不同的数据/地址/回调PARAMS类似的结构:

I have over 50 AJAX calls from different functions of my code. All these calls have a similar structure with different data/url/callback params:

var jqXHR = $.post('/dba/port.php', {
        mode: "del_wallfunds",
        pdata: cdata,
        wname: wName
    },
    function (data) {}, "json")
    .done(function (data) {
        var msg = data.msg;
        if (msg.indexOf("Error") == -1) {
            alertify.success(msg);
            delSelected(selGroup);
        } else {
            alertify.error(msg);
        }
    })
    .fail(function () {
        alertify.error("Error .....");
    });

我在想怎么写,将返回VAR jqXHR减少的code总规模的函数。这是不是一个问题,通过所有的静态变量,如URL,错误字符串等的但问题是,在.done所有的回调函数都不同,我不知道如何通过这些回调作为变量。

I am thinking how to write a function that would return that var jqXHR to minimize the total size of the code. It is not a problem to pass all static variables like URL, error strings etc. But the problem is that all callback functions on ".done" are different and I don't know how to pass these callback functions as variables.

一种方法是调用.done一个通用的功能,并通过一个开关变量的函数,但它似乎并没有成为一个优雅的解决方案。

One way would be to call a single "universal" function on .done and pass a "switch" variable to that function, but it doesn't seem to be an elegant solution.

在一些优雅的方式如何将它有什么建议?

Any suggestions how to it in some elegant way?

感谢

推荐答案

无论哪种呼唤你的功能,当通过完成回调函数作为参数:

Either pass the done callback function as an argument when calling your function:

function ajaxCall(url, data, doneCallback) {
    return $.post(url, data, doneCallback, "json").fail(...);
    // or
    return $.post(url, data, function() {}, "json").done(doneCallback).fail(...);
}

var jqXhr = ajaxCall('yoururl.php', {key: 'value'}, function(data) {
    // do something
});

或者从函数返回的jqXhr对象,并指定完成回调,则:

function ajaxCall(url, data) {
    return $.post(url, data, function() {}, "json").fail(...);
}

var jqXhr = ajaxCall('yoururl.php', {key: 'value'});
jqXhr.done(function(data) {
    // do something
});

或者切换到使用 jQuery.ajax()代替,并通过在整个方案中的对象:

Alternatively switch to using jQuery.ajax() instead, and pass the entire options object in:

function ajaxCall(options) {
    return $.ajax(options).fail(...);
}

var jqXhr = ajaxCall({
    url: 'yoururl.php',
    data: {key: 'value'},
    dataType: 'json'
});
jqXhr.done(function(data) {
    // do something
});

这篇关于如何优化(最小化)jQuery的AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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