javascript - Generic $.ajax() call function for resusability - Stack Overflow

I am creating a application where I have lot of ajax calls to a remote server and use them extensively.

I am creating a application where I have lot of ajax calls to a remote server and use them extensively. As the code is almost same in all calls, I want to create a new function which I can reuse. I am struck up in defining the parameter structure for the "data" parameter. I will explain below my problem.

Sample of my current ajax call is provided below.

Current Call Sample:

$.ajax({
    beforeSend: function() {
        $.mobile.loading('show');
    },
    plete: function() {
        $.mobile.loading('hide');
    },
    type: 'GET',
    url: 'http://localhost/test-url/',
    crossDomain: true,
    data: {appkey: '1234567', action: 'action1','name':'me'},
    dataType: 'jsonp',
    contentType: "application/javascript",
    jsonp: 'callback',
    jsonpCallback: 'mycallback',
    async: false,
    error: function() {
        //some operations
    },
    success: function(data) {
        //some operations
    }
});

The re-usable function that I have created:

function newAjax(parm, successCallback, errorCallback) {
    $.ajax({
        beforeSend: function() {
            $.mobile.loading('show');
        },
        plete: function() {
            $.mobile.loading('hide');
        },
        type: 'GET',
        url: 'http://localhost/test-url',
        crossDomain: true,
        data: {appkey: '1234567', parm: parm},
        dataType: 'jsonp',
        contentType: "application/javascript",
        jsonp: 'callback',
        jsonpCallback: 'mycallback',
        async: false,
        success: function() {
            successCallback();
        },
        error: function() {
            errorCallback();
        }
    });
}

Question:

  • I will be passing the the parameters for the ajax call via "parm" parameter. I want the data value to be directly added to the parent "data" parameter. And not as a sub-object of data. The appKey remains same across all calls and so I keep it in the actual function.

  • I want both the success and error callback functions to be optional. If not provided they should be ignored.

I am creating a application where I have lot of ajax calls to a remote server and use them extensively. As the code is almost same in all calls, I want to create a new function which I can reuse. I am struck up in defining the parameter structure for the "data" parameter. I will explain below my problem.

Sample of my current ajax call is provided below.

Current Call Sample:

$.ajax({
    beforeSend: function() {
        $.mobile.loading('show');
    },
    plete: function() {
        $.mobile.loading('hide');
    },
    type: 'GET',
    url: 'http://localhost/test-url/',
    crossDomain: true,
    data: {appkey: '1234567', action: 'action1','name':'me'},
    dataType: 'jsonp',
    contentType: "application/javascript",
    jsonp: 'callback',
    jsonpCallback: 'mycallback',
    async: false,
    error: function() {
        //some operations
    },
    success: function(data) {
        //some operations
    }
});

The re-usable function that I have created:

function newAjax(parm, successCallback, errorCallback) {
    $.ajax({
        beforeSend: function() {
            $.mobile.loading('show');
        },
        plete: function() {
            $.mobile.loading('hide');
        },
        type: 'GET',
        url: 'http://localhost/test-url',
        crossDomain: true,
        data: {appkey: '1234567', parm: parm},
        dataType: 'jsonp',
        contentType: "application/javascript",
        jsonp: 'callback',
        jsonpCallback: 'mycallback',
        async: false,
        success: function() {
            successCallback();
        },
        error: function() {
            errorCallback();
        }
    });
}

Question:

  • I will be passing the the parameters for the ajax call via "parm" parameter. I want the data value to be directly added to the parent "data" parameter. And not as a sub-object of data. The appKey remains same across all calls and so I keep it in the actual function.

  • I want both the success and error callback functions to be optional. If not provided they should be ignored.

Share Improve this question asked Nov 11, 2013 at 16:39 PurusPurus 5,8299 gold badges55 silver badges92 bronze badges 5
  • just a note, contentType: "application/javascript", doesn't make sense (you're sending GET params to the server, not javascript...), and crossDomain: true, is almost never needed. Also, since you're properly using callbacks, async: false isn't needed. Lastly, since you're using jsonp, none of the aforementioned parameters are used anyway. – Kevin B Commented Nov 11, 2013 at 16:43
  • You need to look at extend()... api.jquery./jQuery.extend – Reinstate Monica Cellio Commented Nov 11, 2013 at 16:45
  • 3 Why reinvent the wheel? jQuery.ajaxSetup – epascarello Commented Nov 11, 2013 at 16:45
  • It looks like you're just throwing everything you can think of into the request without understanding what the parameters do. – Kevin B Commented Nov 11, 2013 at 16:48
  • The request does a cross-domain call so I added those parameters. It uses jsonp, so I read somewhere to use the contentType.. I am learning all these stuffs.. so excuse me for my errors :) – Purus Commented Nov 11, 2013 at 16:54
Add a ment  | 

1 Answer 1

Reset to default 5
  1. You can use the jQuery.extend method to bine two or more objects together.

    data: jQuery.extend({appkey: '1234567'}, parm),
    
  2. You can check that you were actually passed functions for successCallback and errorCallback using typeof var === 'function';

    success: function () {
        if (typeof successCallback === 'function') {
            successCallback();
        }
    }, 
    
    error: function () {
        if (typeof errorCallback === 'function') {
            errorCallback();
        }
    }
    

    ... although it might be nicer if you just returned the Promise created by the AJAX request, and let the caller add their success, error handlers if they wanted;

    function newAjax(parm) {
       return jQuery.ajax({
           /* as before, but without success and error defined */
       });
    }
    

    ... then:

    newAjax().done(function () {
        // Handle done case
    }).fail(function () {
        // Handle error case.
    });
    

    If a caller doesn't want to add an error handler, they just don't call fail();

    newAjax().done(function () {
        // Handle done case
    });
    

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745673919a4639569.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信