目标:
完成:每隔5秒通过AJAX帖子刷新我的页面上的div
不完整 - 当刷新的div上的下拉菜单打开时,请停止刷新div。在刷新的div上关闭下拉菜单时,开始刷新。
使用我当前的代码,abort_refresh()函数似乎不会中止ajax请求。有没有碰巧知道如何使这个工作?
这是我目前拥有的java脚本代码:
function refresh_recent() {
var ajaxFn = $.ajax({
url : '<?php echo site_url('/dashboard/recent'); ?>',
type: "POST",
cache: false,
data : 'none',
success: function(data, textStatus, jqXHR)
{
$('#recent').html(data);
setTimeout(refresh_recent, 5000);
}
});
return ajaxFn;
}
var refresh_object = refresh_recent();
function abort_refresh() {
refresh_object.abort();
}
function start_refresh() {
refresh_object = refresh_recent()
}
&#34;更新内容&#34; JavaScript&amp; HTML
<script type="text/javascript">
$('.refresh').on('shown.bs.dropdown', function () {
abort_refresh();
});
$('.refresh').on('hide.bs.dropdown', function () {
start_refresh();
});
</script>
<div class="refresh btn-group">
<button type="button" class="btn btn-xs btn-danger" data-toggle="modal" data-target="#view-modal" data-type="outbound" data-record="<?php echo $value['id'] ?>"><span class="glyphicon glyphicon-search"></span></button>
<button type="button" class="btn btn-xs btn-danger dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a data-toggle="modal" data-target="#resend-modal" data-record="<?php echo $value['id'] ?>"><span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span>Resend</a></li>
<li class="divider"></li>
<li><a data-toggle="modal" data-target="#delete-outbound-modal" data-record="<?php echo $value['id'] ?>"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span>Delete</a></li>
</ul>
</div>
答案 0 :(得分:2)
失败是因为您没有更新包含Ajax请求的变量。 refresh_object
并不总是有最新请求。另外,您需要取消超时。
(function() {
var refresh_object, timer;
function refresh_recent() {
if (refresh_object) return;
var ajaxFn = $.ajax({
url : '<?php echo site_url('/dashboard/recent'); ?>',
type: "POST",
cache: false,
data : 'none',
success: function(data, textStatus, jqXHR)
{
$('#recent').html(data);
timer = setTimeout(refresh_recent, 5000);
refresh_object = null;
}
});
refresh_object = ajaxFn;
}
refresh_recent();
function abort_refresh() {
if (refresh_object ) {
refresh_object.abort();
}
window.clearTimeout(timer);
refresh_object = null;
}
function start_refresh() {
refresh_recent()
}
$('.refresh')
.on('shown.bs.dropdown', abort_refresh)
.on('hide.bs.dropdown', start_refresh);
}());