2012-05-18 126 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