php - YouTube API 循环问题

标签 php jquery ajax html

我的 YouTube API 脚本出现循环问题。下面的代码显示了我的代码。我遇到的问题是,在我通过 jquery ajax 从服务器获得响应后,我会提醒所选特定视频的 YouTube ID。出于某种原因,它会提醒它三次。我尝试修改代码,在循环外添加 ajax 调用,但它似乎不起作用。任何帮助将不胜感激。

下面是app.js

function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}

$(function() {
    $("form").on("submit", function(e) {
       e.preventDefault();
       // prepare the request
       var request = gapi.client.youtube.search.list({
            part: "snippet",
            type: "video",
            headers: {referer: "//localhost/"},
            q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
            maxResults: 3 // Set this to the number you want to display on the page.
       });
       // execute the request
       request.execute(function(response) {
          var results = response.result;
          $("#results").html("");
          $.each(results.items, function(index, item) {

            $.get("tpl/item.html", function(data) {


                $("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));



                $('.selection').on('click', function () {

                    let url = "update_db.php";
                    let song_name2 = item.snippet.title;
                    let youtube_id = item.id.videoId;

                    $.ajax({
                        dataType: "JSON",
                        url: url,
                        type: "GET",
                        data: {song_name2: song_name2, youtube_id: youtube_id},
                        success: function (data) {

                            alert("YouTube ID: " + youtube_id );
                            //ALERTS 3 TIMES. HOW TO FIX IT???
                            /*if(data.msg === "success"){
                                console.log(data.result);
                                alert(data.result);
                            } else {
                                console.log(data.result);
                                alert(data.result);
                            }*/
                        }
                    });
                });

            });

          }); // for each loop
          resetVideoHeight();
       });
    });

    $(window).on("resize", resetVideoHeight);
});

function resetVideoHeight() {
    $(".video").css("height", $("#results").width() * 9/16);
}

function youtube_api() {
    gapi.client.setApiKey("PUBLIC KEY");
    gapi.client.load("youtube", "v3", function() {
        // yt api is ready
    });
}

下面是item.html

<div class="item">
    <h2>Title: <strong><span style="color: red">{{title}}</span></strong></h2>
    <h2><span class="selection">I will like to perform this selection</span></h2>
    <iframe class="video w100" width="640" height="360" src="https://www.youtube.com/embed/{{videoid}}" frameborder="0" allowfullscreen></iframe>

</div>`enter code here`

下面是index.html

<!DOCTYPE html>
<html lang="en">
    <head>      
        <title>Search your YouTube video</title>
        <meta charset="UTF-8" />                    
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Awesome videos!" />
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>

        <div class="row con">

            <div class="col-md-6 col-md-offset-4">
                <div style="width: 47%; height: 50px; margin-left: 22px; display: none" id="success" class="alert-success text-center"><div  style="padding-top: 15px; padding-right: 15px;"></div></div>

                <div style="width: 47%; height: 50px; margin-left: 22px; display: none" id="error" class="alert-danger text-center"><div style="padding-top: 15px; padding-right: 15px;"></div></div>

                <form>
                    <p><input type="text" id="search" placeholder="Search YouTube video" autocomplete="off" class="form-control" required /></p>
                    <p>
                        <button type="submit" id="youtube_video_search" class="form-control btn btn-primary w100">
                            <span class="glyphicon glyphicon-search"></span> Search
                        </button>
                    </p>
                </form>

            </div>
        </div>
        <div class="row">
            <div class=" col-md-6 col-md-offset-3">
                <div id="results"></div>
            </div>

        </div>

        <!-- scripts -->
        <script src="./jquery-3.3.1.js"></script>
        <script src="js/app.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=youtube_api"></script>
    </body>
</html>

最佳答案

For some reason, it alerts it three times.

您正在绑定(bind) click.selection在每个循环上以及循环完成后,您有 3 个元素 .selection ,这意味着您将点击绑定(bind)到所有 3 个。

你应该把它绑定(bind)在id上或一些自定义标签,如 data-selection-id=UNIQUE_ID

item.html

更改 <span class="selection"><span class="selection" data-selection-id="{{videoid}}">

app.js

更改 $('.selection').on('click', function () {$('.selection[data-selection-id="+ item.id.videoId +"]').on('click', function () {

关于php - YouTube API 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52733584/

相关文章:

javascript - jQuery 中连接到单选按钮的特定输入验证

javascript - 从 HTMLTableRowElement 中的特定单元格获取子元素并隐藏/删除它们?

javascript - 提交后重置表单

javascript - JQMobile - 无法在自定义 ajax 中加载微调器

php - 为什么 PHP preg_* 函数需要正则表达式分隔符?

PHP GD 捆绑扩展无需重新编译 PHP - 解决方案

javascript - 单击时可下载文件的超链接,并为每次下载增加一个字段

php - 如何知道选择了哪个 mysqli_fetch_assoc 行

javascript - jQuery $(this) 不会将文本插入到我的元素中

jquery - 如何用jquery清空文本区域中的消息?