【问题标题】:Ajax form submitting multiple times. SometimesAjax 表单提交多次。有时
【发布时间】:2012-05-26 07:06:10
【问题描述】:

我正在使用 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 事件之前,但这并没有解决问题。

【问题讨论】:

    标签: php jquery ajax forms submit


    【解决方案1】:

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

    【讨论】:

    • 这不是只有在提交表单时才会触发吗?
    • 是的,它会在表单提交时触发,但是由于您一次又一次地重新加载此页面,因此多个侦听器正在附加
    • 如果我添加 $("#send_msg_form").die('submit'); to
    • 这样当页面刷新时“解除绑定”?我是 jquery 的新手,请原谅我的无知。
    • 这似乎是一个合理的解决方案,但如果你不重新加载你的回复块,你的听众不会被激活,所以记得重新加载你的回复块
    猜你喜欢
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2015-04-04
    • 1970-01-01
    相关资源
    最近更新 更多