我的间隔不会停止,当我点击我的提交按钮,然后开始间隔。
我正在建立一个聊天系统,它应该一遍又一遍地重新加载聊天,但是当聊天重新加载运行时,消息提交非常慢,所以它应该在消息提交运行时停止聊天重新加载,并且然后再开始。
脚本:
<script>
$(document).ready(function(){
function auto_load(){
$.ajax({
url: "index.php?url=userchat1&id=1",
cache: false,
success: function(data){
$("#chatdiv").html(data);
}
});
}
auto_load();
//Refresh auto_load() function after 500 milliseconds
var myVar = setInterval(function(){ auto_load() }, 500);
$('#beskedform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'index.php?url=chatsubmit&id=1',
data: $('#beskedform').serialize(),
success: function () {
$("#msg").attr('value','');
$("#msg").removeAttr('disabled');
$("#msgbutton").removeAttr('disabled');
var myVar = setInterval(function(){ auto_load() }, 500);
}
});
clearInterval(myVar);
$("#msg").attr('disabled','disabled');
$("#msgbutton").attr('disabled','disabled');
});
});
</script>
HTML:
<form id="beskedform">
<textarea name="msg" id="msg" class="form-control content-group" rows="3" cols="1" placeholder="Skriv din besked..."></textarea>
<div class="row">
<div class="col-xs-6">
</div>
<div class="col-xs-6 text-right">
<button type="submit" id="msgbutton" class="btn bg-teal-400 btn-labeled btn-labeled-right"><b><i class="icon-circle-right2"></i></b> Send</button>
</div>
</div>
</form>
答案 0 :(得分:0)
请使用此脚本。
<script>
$(document).ready(function(){
function auto_load(){
$.ajax({
url: "index.php?url=userchat1&id=1",
cache: false,
success: function(data){
$("#chatdiv").html(data);
}
});
}
auto_load();
//Refresh auto_load() function after 500 milliseconds
var myVar = setInterval(function(){ auto_load() }, 500);
$('#beskedform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'index.php?url=chatsubmit&id=1',
data: $('#beskedform').serialize(),
success: function () {
$("#msg").attr('value','');
$("#msg").removeAttr('disabled');
$("#msgbutton").removeAttr('disabled');
myVar = setInterval(function(){ auto_load() }, 500);
}
});
clearInterval(myVar);
$("#msg").attr('disabled','disabled');
$("#msgbutton").attr('disabled','disabled');
});
});