我有“加载更多”按钮,如果我单击它的速度足够快,它会加载相同的内容两次,我想阻止它。
这就是我如何使用 ajax 调用加载更多:
<script type="text/javascript">
function loadmore() {
var val = document.getElementById("result_no").value;
var userval = document.getElementById("user_id").value;
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
getresult: val,
getuserid: userval
},
context: this,
success: function(response) {
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML + response;
document.getElementById("result_no").value = Number(val) + 10;
}
});
}
</script>
<div id="content">
<div id="result_para">
</div>
</div>
<input type="hidden" id="user_id" value="<?php echo $userid;?>">
<input type="hidden" id="result_no" value="15">
<input type="button" id="load" onclick="loadmore()" value="Load More Results">
最佳答案
您可以在 loadmore
开始时将 loading
变量设置为 true,并在 ajax 回调中将其设置回 false。不过,loading
应该在 loadmore
之外声明(看看什么是闭包)。
var loading = false;
function loadmore()
{
if (loading) {
return ;
}
loading = true;
var val = document.getElementById("result_no").value;
var userval = document.getElementById("user_id").value;
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
getresult:val,
getuserid:userval
},
context: this,
success: function (response) {
loading = false;
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML+response;
document.getElementById("result_no").value = Number(val)+10;
},
error: function () {
loading = false;
}
});
}
您还可以通过编程方式禁用/启用该按钮,而不是使用该变量,但这意味着如果请求很快,您的按钮将会闪烁。
关于javascript - 防止ajax的多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36534014/