简体   繁体   中英

ajax best practice

let's say i have the following HTML page.

<A panel to display list of items>
  Item A
  Item B
  Item C
  ...

<A panel to display details about item>
  Details on item X:

I want to write the page so that whenever the user clicks on one of the items, the detail about the selected item will show up on the bottom panel.

However, few problems that I want to solve are:

  • How should I prevent duplicate requests. (like, user presses links to item A and B before the detail of item A returns from the server).
  • If I want to display "detail is now loading...", where should I put the code?

you can register click handlers, which fire ajax requests to load the data.

There are multiple ways to handle your concern about not firing multiple requests:

  1. Just unregister the handlers on the other Items when you click one of them, and put them back when your request returns.
  2. You can have an object in the scope of the request handlers that you set a property on, like 'requestInProgress', that you set to true and false appropriately. In other words, use closures.

Displaying 'detail is now loading' is simple -- you can just set the value of the Panel dom, or the innerhtml if you want, to that message before you fire the request, and set the actual returned value when the request returns.

Note that many js libraries, like jQuery, provide an API around making ajax requests that might simplify things. For example, the jQuery.ajax method takes an object literal that can contain the functions 'beforeSend', 'complete', 'success' so you do things before, after, and on the case of success (among other functions, check out http://api.jquery.com/jQuery.ajax/ )

You can certainly do what you want with bare-metal js, but libraries can make your life easier.

About duplicate requests, I'd keep the last XMLHttpRequest object inside a lastRequest variable. Whenever I'm sending a new request I'd check this variable. If it exists, call lastRequest.abort() . I'd also check in your success callback that the request object is the same as your lastRequest , otherwise ignore it. In jQuery this would look like:

var lastRequest;

// Your click handler
$(".items").click(function () {
   if (lastRequest) lastRequest.abort();
   lastRequest = $.ajax({..., success: function (data, status, request) {
      if (request != lastRequest) return; // Ignore, it was aborted

      // Code to show the detail about the selected item
   }});

   // Code to show the in-progress message
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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