最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to optimize (minimize) jQuery AJAX calls - Stack Overflow

programmeradmin2浏览0评论

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

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.

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?

Thanks

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

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.

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?

Thanks

Share Improve this question asked Oct 23, 2013 at 8:16 user2723490user2723490 2,1004 gold badges28 silver badges37 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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

Or return the jqXhr object from the function, and assign the done callback then:

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

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

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

You can try to :

  • turn "request successfully returned a treatment error" into a "rejected request",
  • put the "alertify" processing in a mon callback

Here is a sketch of what this could give :

function myAjaxApi(url, data){
    var myAjaxCall = $.post(url, data, function (data) {}, "json")
    .then(function (data) {
    // using .then : change "request succesful with error state"
    //    to "rejected state"
        var msg = data.msg;
        if (msg !== undefined && msg.indexOf("Error") >= 0) {
            var dfd = $.Deferred();
        // try to match the same signature as the "error" option
            dfd.reject(this, msg);
            return dfd;
        } else {
            return data
        }
    });

    myAjaxCall.done(function(data){
        if (data.msg) {
            alertify.success(data.msg);
        }
    }).fail(function (jqxhr, msg) {
        if (!msg) {  msg = "Error .....";  }
        alertify.error(msg);
    });
    return myAjaxCall;
}

//usage
myAjaxApi('/dba/port.php', {mode: "del_wallfunds", pdata: cdata, wname: wName})
.done(function (data) {
// the ".done()" queue will not be executed if msg contains "Error" ...
    delSelected(selGroup);
});

Some parts should be written with more care ; the above example is meant to illustrate how you can wrap your repeated ajax calls inside a mon api.

发布评论

评论列表(0)

  1. 暂无评论