JS / AJAX:提交表单时没有按钮点击/页面刷新问题

时间:2012-07-13 04:58:32

标签: javascript jquery

我正在尝试提交视频网址并返回嵌入代码而不刷新页面或按钮。我有js函数,它将获取输入框的值。问题是,该函数不会提交将回显嵌入代码的表单。如何在没有按钮单击或刷新的情况下提交表单,以便它可以回显php代码?

EXAMPLE

JS无需刷新即可提交

            <script>
            $(document).ready(function() {
                                    var timer;
                                        $('#video-input1').on('keyup', function() {
                                            var value = this.value;

                                            clearTimeout(timer);

                                            timer = setTimeout(function() {

                                                //do your submit here
                                                $("#ytVideo").submit()

                                                alert('submitted:' + value);
                                            }, 2000);
                                        });


                 //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('index.php', form, function(data){ 


                       });
                  });

            });
            </script>

HTML

<html>
    <form  method="post" id="ytVideo" action="">
    Youtube URL:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id="video-input1" type="text" value="<?php $url ?>" name="yurl">   
    </form>
</html>

PHP

  <?php

    if($_POST)
    {
        $url     = $_POST['yurl'];


        function getYoutubeVideoID($url) {
            $formatted_url = preg_replace('~https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/| youtube\.com\S*[^\w\-\s])([\w\-]{11})      
                    (?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>| </a>))[?=&+%\w-]*~ix','http://www.youtube.com/watch?v=$1',$url);
            return $formatted_url;
        }
        $formatted_url = getYoutubeVideoID($url);
        $parsed_url = parse_url($formatted_url);




        parse_str($parsed_url['query'], $parsed_query_string);
        $v = $parsed_query_string['v'];

        $hth        = 300; //$_POST['yheight'];
        $wdth       = 500; //$_POST['ywidth'];


//Iframe code

echo htmlentities ('<iframe src="http://www.youtube.com/embed/'.$v.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');

}
?>

1 个答案:

答案 0 :(得分:1)

尝试在.submit()处理程序的末尾添加return false

$('#ytVideo').submit(function(e){
   ...
   $.post(..., function() {

   });

   return false; // add this
});