[英]ajax best practice
let's say i have the following HTML page. 假设我有以下HTML页面。
<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: 但是,我想要解决的问题很少:
you can register click handlers, which fire ajax requests to load the data. 您可以注册单击处理程序,这些处理程序将触发ajax请求以加载数据。
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. 显示'detail is now loading'很简单 - 您可以在触发请求之前将Panel dom或innerhtml的值设置为该消息,并在请求返回时设置实际返回值。
Note that many js libraries, like jQuery, provide an API around making ajax requests that might simplify things. 请注意,许多js库(如jQuery)提供了围绕发出可能简化操作的ajax请求的API。 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/ ) 例如,jQuery.ajax方法接受一个对象文字,它可以包含函数'beforeSend','complete','success',因此你可以在成功之前,之后和之后做一些事情(除了其他函数之外,请查看http ://api.jquery.com/jQuery.ajax/ )
You can certainly do what you want with bare-metal js, but libraries can make your life easier. 您当然可以使用裸机js做您想做的事,但是库可以使您的生活更轻松。
About duplicate requests, I'd keep the last XMLHttpRequest object inside a lastRequest
variable. 关于重复请求,我将最后一个XMLHttpRequest对象保留在lastRequest
变量中。 Whenever I'm sending a new request I'd check this variable. 每当我发送新请求时,我都会检查这个变量。 If it exists, call lastRequest.abort()
. 如果存在,则调用lastRequest.abort()
。 I'd also check in your success callback that the request object is the same as your lastRequest
, otherwise ignore it. 我还会检查你的成功回调,请求对象与你的lastRequest
相同,否则忽略它。 In jQuery this would look like: 在jQuery中,这看起来像:
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.