Ajax表单多次提交。有时

时间:2012-05-18 17:31:20

标签: php jquery ajax forms submit

我正在使用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次。非常奇怪,之前我已经构建了类似页面并且从未遇到过这个问题。我知道这是我的代码,永无止境的刷新,但这是我目前唯一的选择。有人看到这个问题吗?

我在提交表单时尝试在.live事件之前放置.die()但是没有解决问题。

1 个答案:

答案 0 :(得分:0)

您正在重新加载回复块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;
   }
}