最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin9PV0评论

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
    });
    
Post a comment

comment list (0)

  1. No comments so far