在用户将Youtube链接粘贴到输入后运行的Jquery函数(Ajax)


Jquery function that runs after an user has pasted a Youtube link in an input (Ajax)

这是将从中提取url值的HTML。

<p align="center">Youtube video</p>
<div class="row collapse">
    <div class="small-3 large-2 columns">
    <span class="prefix">http://</span>
    </div>
    <div class="small-9 large-10 columns">
    <input type="url" id="thread_url" placeholder="Youtube link...">
    </div>
</div>
<div id="dynamicPreview">
    <iframe width="320" height="240" src="" frameborder="0" class="hide"></iframe>
</div>

这是一个php函数,用于从youtube链接获取视频id。

    public function getYoutubeVideoId($url) {
    $pattern = '%^# Match any youtube URL
    (?:https?://)?  # Optional scheme. Either http or https
    (?:www'.)?      # Optional www subdomain
    (?:             # Group host alternatives
      youtu'.be/    # Either youtu.be,
    | youtube'.com  # or youtube.com
      (?:           # Group path alternatives
        /embed/     # Either /embed/
      | /v/         # or /v/
      | /watch'?v=  # or /watch'?v=
      )             # End path alternatives.
    )               # End host alternatives.
    (['w-]{10,12})  # Allow 10-12 for 11 char youtube id.
    $%x';
    $result = preg_match($pattern, $url, $matches);
    if (false !== $result) {
        return $matches[1];
    }
    return false;

如何得到一个Jquery脚本运行后,用户已经粘贴了一个Youtube链接,以及如何ajax函数必须看起来为了它自动运行

您需要检查文本是否更改为:

<p align="center">Youtube video</p>
<div class="row collapse">
    <div class="small-3 large-2 columns">
    <span class="prefix">http://</span>
    </div>
    <div class="small-9 large-10 columns">
    <input type="url" id="thread_url" placeholder="Youtube link...">
    </div>
</div>
<div id="dynamicPreview">
    <iframe width="320" height="240" src="" frameborder="0" class="hide"></iframe>
</div>
<script type="text/javascript">
        $('body').delegate('#thread_url','keyup',function() {
            $.post( "youtube_function.php", {url: $(this).val() })
               .done(function( data ) {
                if(data) {
                   //Its a youtube link
                }
             });
        });
</script>