喵-见缝插针 2018-10-10 06:04 采纳率: 0%
浏览 29

YouTube API循环问题

I am having a looping issue with my YouTube API script. The code below shows my code. The issue that I am having is that after I get a response back from the server through jquery ajax, I alert the YouTube ID of a selected specific video. For some reason, it alerts it three times. I tried modifying the code adding the ajax call outside of the loop, but it doesn't seem to work. Any help would be greatly appreciated.

Below is the 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
    });
}

Below is the 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`

Below is the 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>
  • 写回答

2条回答 默认 最新

  • weixin_33739523 2018-10-10 06:33
    关注

    Not exactly sure your case, But for a workaround you can handle this with any boolean flag.

    $('.selection').on('click', function () {
    
    var isExecuted = false;
    
    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) {
    
           if(!isExecuted)
           {
               isExecuted = true;
               alert("YouTube ID: " + youtube_id );
               //ALERTS 3 TIMES. HOW TO FIX IT???
           }
       }
      });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?