Reputation: 6078
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:
Upvotes: 0
Views: 347
Reputation: 93664
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
});
Upvotes: 0
Reputation: 120168
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:
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.
Upvotes: 2