小编典典

JS / AJAX:使用计时器提交表单,而不是单击按钮或刷新页面

ajax

我正在尝试提交没有页面刷新或提交按钮的表单。但是我只实现了让JS函数提交输入框值。是否可以在不单击按钮和刷新页面的情况下提交整个表单?

JSFIDDLE

JS

            <script type="text/javascript">
                $(document).ready(function() {
                    var timer;
                        $('#yurl).on('keyup', function() {
                            var value = this.value;

                            clearTimeout(timer);

                            timer = setTimeout(function() {

                                //do your submit here

                                alert('submitted:' + value);
                            }, 2000);
                        });
                });
            </script>

html

                <form method="post" id="ytVideo" action="">
                <input id="yurl" type="text" value="<?php $url ?>" name="yurl">     
                </form>

阅读 245

收藏
2020-07-26

共1个答案

小编典典

您的小提琴似乎正在工作,但是问题是您没有真正将其提交到任何地方。

<script type="text/javascript">
 $(document).ready(function() {
                        var timer;
                            $('#yurl).on('keyup', function() {
                                var value = this.value;

                                clearTimeout(timer);

                                timer = setTimeout(function() {

                                    //do your submit here
                                    $("#ytVideo").submit()
                                    alert('submitted:' + value);
                                }, 2000);
                            });


     //then include your submit definition. What you want to do once submit is executed
      $('#ytVideo').submit(function(e){
           e.preventDefault(); //prevent page refresh
           var form = $('#ytVideo').serialize();
           //submit.php is the page where you submit your form
           $.post('submit.php', form, function(data){ 
              //do something with the data

           });
      });

});
</script>
2020-07-26