2012-05-18 89 views
2

我正在使用Malsup的AJax表单插件。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(),但没有解决问题。

回答

0

重新装入这是造成这片被触发回复块格,每个负载多一个监听器获取添加

$('#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; 
    } 
} 
+0

隐而不宣只有在提交表单时才会触发这种情况? – DanielOlivasJr

+0

是的,它会在表单提交时被触发,但是因为您一次又一次地重新加载此页面,多个侦听器正在连接 – mprabhat

+0

如果我添加$(“#send_msg_form”)。到 DanielOlivasJr