YouTube API循环问题

时间:2018-10-10 06:04:15

标签: php jquery ajax html5

我的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>

2 个答案:

答案 0 :(得分:1)

  

由于某种原因,它会发出三次警报。

您在每个循环上都将click上的.selection绑定在一起,当循环完成时,您将有3个元素与.selection绑定,这意味着您要绑定所有3个元素的点击。

您应将其绑定到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 () {

答案 1 :(得分:0)

不确定您的情况,但是对于解决方法,您可以使用任何布尔标志来处理。

$('.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???
       }
   }
  });
});