简体   繁体   English

重构许多jQuery Ajax调用 - 最佳实践?

[英]Refactoring many jQuery Ajax calls - best practice?

I have a lot of JavaScript/ jQuery code blocks to handle asynchronous data processing in my page. 我有很多JavaScript / jQuery代码块来处理我页面中的异步数据处理。 Each code block has three functions (code is incomplete and for illustrative purpose only): 每个代码块都有三个函数(代码不完整,仅用于说明目的):

  1. encapsulates $.ajax call: 封装$.ajax调用:

     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). 可以有一个错误处理程序可以在Ajax调用中重用(显而易见)。
  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?). 也许创建一些提供基本功能的原型对象,并有一个静态的错误处理方法(这可以在JavaScript中完成吗?)。

I was just wondering if anyone has come across this and/or if there is a best practice solution for this? 我只是想知道是否有人遇到过此问题和/或是否有针对此的最佳实践解决方案?

You can use the $.ajaxSetup({}) method in jQuery to setup some common ajax settings. 您可以在jQuery中使用$ .ajaxSetup({})方法来设置一些常见的ajax设置。

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. 例如,如果您要在某个页面上反复发布到同一个URL,则可以在ajaxSetup中进行设置。 This would mean you would have to pass less parameters to a function like what Richard provided. 这意味着您必须将更少的参数传递给Richard提供的函数。 Any property of the ajax method's first parameter can be set as a default in $.ajaxSetup(). ajax方法的第一个参数的任何属性都可以设置为$ .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. 它们可以在任何ajax调用中被覆盖。 So, now you can just do: 所以,现在你可以这样做:

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

And you can override the URL, for instance like this: 你可以覆盖URL,例如:

$.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: 我们经常使用包装器函数进行Ajax调用以简化使用,因此您可以这样做:

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: 但我经常更喜欢使用jQuery ajax事件绑定到每个ajax事件:

http://docs.jquery.com/Ajax http://docs.jquery.com/Ajax

so you could bind to every failure or success of every ajax call such as: 所以你可以绑定每个ajax调用的每个失败或成功,例如:

ajaxError( callback ) ajaxSuccess( callback ) ajaxError(回调)ajaxSuccess(回调)

As Richard shows, look at what is different between the code snippets and pass them in as parameters to a function. 正如Richard所示,查看代码片段之间的不同之处,并将它们作为参数传递给函数。 Javascript can pass functions around as parameters, which can get rid of a great deal of redundancy. Javascript可以将函数作为参数传递,这可以消除大量冗余。

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. 如果url没有改变,那么为什么将它作为参数传递,你可以有一个全局变量,它将包含url的主要部分,并且只传入更改的url部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM