我正在使用Malsup的AJax表单插件。
我要做的是一个"聊天"页面,基本上是一个每 2 秒刷新一次的div,并在用户向聊天窗口提交内容时刷新。
页面的粗略 HTML 布局:
<div id='refresh_openmsg'>
<div id='chatdiv'>Chat window here</div>
</div>
<div id='reply_block'>
<form id='send_msg_form'>Basic form goes here</form>
</div>
.JS:
//create timer to refresh chat window every 2 seconds
<script type='text/javascript'>
$(document).ready(function() {
refresh_openmsg = setInterval(function (){$('#refresh_openmsg').load('messaging.php?view='+the_page+' #refresh_openmsg');}, 2000);
});
</script>
//This is what happens when the form is submitted
<script type='text/javascript'>
$(document).ready(function() {
var options = {
target: '',
dataType: 'html',
beforeSubmit: showRequest_sendmsg,
success: showResponse_sendmsg
};
$('#send_msg_form').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
});
function showRequest_sendmsg(formData, jqForm, options) {
return true;
}
function showResponse_sendmsg(responseText, statusText, xhr, $form) {
$("#reply_block").load('messaging.php?view='+the_page+' #reply_block', function() {
$('#reply_area').focus();
$("#refresh_openmsg").load('messaging.php?view='+the_page+' #refresh_openmsg', function() {
$("html, body").animate({ scrollTop: $(document).height() }, 500);
});
}).focus();
}
</script>
//on showResponse, I'm reloading the #reply_block div, and reloading the #refresh_openmsg div (#refresh_openmsg div is also being reloaded every 2 seconds)
我遇到的问题是表单被多次提交,有时两次,有时 3 次,有时 4 或 5 次。 很奇怪,我以前构建过类似的页面,但从未遇到过这个问题。 我知道这是我的代码,永无止境的刷新,但这是我目前唯一的选择。有人认为这有问题吗?
提交表单时,我尝试将 .die(( 放在 .live 事件之前,但这并没有解决问题。
您正在重新加载回复块div,这导致此片段被触发,因此每次加载后都会添加一个侦听器
$('#send_msg_form').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
您可以尝试像这样使用:
$('#send_msg_form').live('submit', replyBlockDivLoaderHandler);
function replyBlockDivLoaderHandler(event){
if(event.handled != true){
$(this).ajaxSubmit(options);
event.handled = true;
}
}