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

javascript - Refactoring many jQuery Ajax calls - best practice? - Stack Overflow

programmeradmin3浏览0评论

I have a lot of JavaScript/ jQuery code blocks to handle asynchronous data processing in my page. Each code block has three functions (code is inplete and for illustrative purpose only):

  1. encapsulates $.ajax call:

    function doSomething(data){
    
      // do some preprocessing 
    
      $.ajax({}); // some JQuery Ajax operation that accepts data
    
      // do some postprocessing
      return false;
    }
  2. handles the response:

    function handleResponse(result){  
      // process the result
      return false;
    }
  3. handles any error:

    function handleError(XMLHttpRequest, textStatus, errorThrown){  
      // gracefully handle the Error and present relevant information to user
      return false;
    }

In a page that requires a lot of data processing I end up having a lot of these blocks which seems to be duplication, so I decided to do some refactoring.

I figure there would be different ways to go about this.

  1. One could have one error handler that can be reused across Ajax calls (obvious).
  2. One could maybe reuse some response handlers, but this would be akward as responses are very different depending on call.
  3. Maybe create some kind of prototype object that provides base functionality and have a static method for error handling (can this be done in JavaScript?).

I was just wondering if anyone has e across this and/or if there is a best practice solution for this?

I have a lot of JavaScript/ jQuery code blocks to handle asynchronous data processing in my page. Each code block has three functions (code is inplete and for illustrative purpose only):

  1. encapsulates $.ajax call:

    function doSomething(data){
    
      // do some preprocessing 
    
      $.ajax({}); // some JQuery Ajax operation that accepts data
    
      // do some postprocessing
      return false;
    }
  2. handles the response:

    function handleResponse(result){  
      // process the result
      return false;
    }
  3. handles any error:

    function handleError(XMLHttpRequest, textStatus, errorThrown){  
      // gracefully handle the Error and present relevant information to user
      return false;
    }

In a page that requires a lot of data processing I end up having a lot of these blocks which seems to be duplication, so I decided to do some refactoring.

I figure there would be different ways to go about this.

  1. One could have one error handler that can be reused across Ajax calls (obvious).
  2. One could maybe reuse some response handlers, but this would be akward as responses are very different depending on call.
  3. Maybe create some kind of prototype object that provides base functionality and have a static method for error handling (can this be done in JavaScript?).

I was just wondering if anyone has e across this and/or if there is a best practice solution for this?

Share Improve this question edited Feb 11, 2011 at 21:20 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Apr 22, 2009 at 11:38 martijn_himselfmartijn_himself 1,5703 gold badges19 silver badges34 bronze badges 1
  • It would be helpful to see some code. – Ólafur Waage Commented Apr 22, 2009 at 11:43
Add a ment  | 

3 Answers 3

Reset to default 8

You can use the $.ajaxSetup({}) method in jQuery to setup some mon ajax settings.

For instance, if you are going to be posting to the same URL over and over again on some page, you can just set that in the ajaxSetup. This would mean you would have to pass less parameters to a function like what Richard provided. Any property of the ajax method's first parameter can be set as a default in $.ajaxSetup().

$.ajaxSetup({
    url: 'my/ajax/url'
    success: function() {
        // Do some default stuff on success
    },
    error: function() {
        // Do some default stuff on a failure
    }
    // etc...
});

They can be overridden in any ajax call. So, now you can just do:

$.ajax({data:{foo:'bar',bar:'foo'}});

And you can override the URL, for instance like this:

$.ajax({url:'different/ajax/url',data:{foo:'bar',bar:'foo'}});

We have often used a wrapper function for the Ajax call in order to simplify the usage so you could do this:

function NewAjax(url, data, success)
{
    $.ajax({
      url: url,
      data: data,
      success: success,
      fail: function ()
      {
        // Do generic failure handling here
      }
}

But I often prefer to bind to every ajax event using the jQuery ajax events:

http://docs.jquery./Ajax

so you could bind to every failure or success of every ajax call such as:

ajaxError( callback ) ajaxSuccess( callback )

As Richard shows, look at what is different between the code snippets and pass them in as parameters to a function. Javascript can pass functions around as parameters, which can get rid of a great deal of redundancy.

If the url doesn't change though, then why pass it in as a parameter, you could have a global variable that will have the main part of the url, and just pass in the part of the url that changes.

发布评论

评论列表(0)

  1. 暂无评论