我想启动一个AJAX调用,在页面加载时第一次刷新表,但是从那时开始需要它每隔XX秒运行一次,但每当用户按下“刷新”按钮时也是如此。
现在我不想制作相同代码的3个副本并将其绑定到3个不同的发射器,最好的方法是什么?
此处每5秒运行一次,但不会在页面加载或按钮单击
时运行 <script type="text/javascript" language="javascript">
$(function() {
var prevAjaxReturned = true;
var xhr = null;
setInterval(function() {
if( prevAjaxReturned ) {
prevAjaxReturned = false;
} else if( xhr ) {
xhr.abort( );
}
xhr = $.ajax({
type: 'POST',
url: '../../plugins/MySQL/ajax_action.php',
data: {
action: 'refresh_rescap_reqs',
holidex: '<?php echo($_SESSION['Holidex']); ?>',
access: '<?php echo $_SESSION['Access']; ?>'
},
//dataType: 'json',
success: function(data) {
$('#Last20Requests').html(data);
prevAjaxReturned = true;
},
});
}, 5000); // 1000ms = 1 sec
});
</script>
由于
答案 0 :(得分:3)
将函数绑定到变量,然后重复使用它。
<script type="text/javascript" language="javascript">
$(function() {
var prevAjaxReturned = true;
var xhr = null;
var functionToRun = function() {
if( prevAjaxReturned ) {
prevAjaxReturned = false;
} else if( xhr ) {
xhr.abort( );
}
xhr = $.ajax({
type: 'POST',
url: '../../plugins/MySQL/ajax_action.php',
data: {
action: 'refresh_rescap_reqs',
holidex: '<?php echo($_SESSION['Holidex']); ?>',
access: '<?php echo $_SESSION['Access']; ?>'
},
//dataType: 'json',
success: function(data) {
$('#Last20Requests').html(data);
prevAjaxReturned = true;
},
});
};
setInterval(functionToRun, 5000); // 1000ms = 1 sec
$(document).on('click', functionToRun);
functionToRun();
});
答案 1 :(得分:1)
在函数中包装ajax调用并调用此函数3次
$(function() {
var prevAjaxReturned = true;
var xhr = null;
var repeatFunction = function() {
if( prevAjaxReturned ) {
prevAjaxReturned = false;
} else if( xhr ) {
xhr.abort( );
}
xhr = $.ajax({
type: 'POST',
url: '../../plugins/MySQL/ajax_action.php',
data: {
action: 'refresh_rescap_reqs',
holidex: '<?php echo($_SESSION['Holidex']); ?>',
access: '<?php echo $_SESSION['Access']; ?>'
},
//dataType: 'json',
success: function(data) {
$('#Last20Requests').html(data);
prevAjaxReturned = true;
},
});
};
repeatFunction();
setInterval(repeatFunction, 5000); // 1000ms = 1 sec
$("#reload").on('click', repeatFunction);
});
&#13;
<a href="javascript:void(0)" id="reload">Reload</a>
&#13;