[英]Prevent multiple Ajax request (pagination with pushstate)
在那里我遇到了使用HTML API Pushstate进行ajax分页的问题。
所以,这是我的代码:
<ul class="small">
<li>
<p>a</p>
</li>
</ul>
<ul class="paging">
<li><a href=/page2>2</a></li>
<li><a href=/page3>3</a><li>
<li><a href=/page4>4</a><li>
</ul>
$(document).ready(function() {
if (window.history && history.pushState) {
historyedited = false;
$(window).on('popstate', function(e) {
if (historyedited) {
loadProducts(location.pathname + location.search);
}
});
doPager();
}
});
function doPager() {
$('.paging li a').click(function(e) {
e.preventDefault();
loadProducts($(this).attr('href'));
history.pushState(null, null, $(this).attr('href'));
historyedited = true;
});
}
function loadProducts(url) {
$('.small li').empty().load(url + ' .small', function() {
doPager();
});
}
它在第一次点击时效果很好,但当我点击2,或3或4次时,问题出现了。 它产生了多个Ajax请求,而且事情变得越来越糟糕。 我的代码出了什么问题?
点击新页面时,您必须先取消之前的请求。 你不能使用.load(),所以最好使用$ .ajax。 你可以这样做:
$(document).ready(function() {
$('.paging li a').click(function(e) {
e.preventDefault();
// Cancel previous request if there is one
if(typeof xhr !== 'undefined') {
xhr.abort();
}
// Do the new request
var xhr = $.ajax({
url: $(this).attr('href') + '.small',
success: function(data) {
$('.small li').html(data);
doPager();
}
});
});
});
尝试下面的方法
$(document).ready(function() {
if (window.history && history.pushState) {
historyedited = false;$(window).on('popstate', function(e) {
if (historyedited) {
loadProducts(location.pathname + location.search);
}
});
}
$('.paging li a').click(function(e) {
e.preventDefault();
loadProducts($(this).attr('href'));
history.pushState(null, null, $(this).attr('href'));
historyedited = true;
});});
function loadProducts(url){
$('.small li').empty().load(url + ' .small');}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.