У меня проблема с зацикливанием моего сценария API YouTube. В приведенном ниже коде показан мой код. Проблема, с которой я столкнулся, заключается в том, что после того, как я получаю ответ от сервера через jquery ajax, я предупреждаю идентификатор YouTube о выбранном конкретном видео. Почему-то он трижды предупреждает об этом. Я попытался изменить код, добавив вызов 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.info(data.result);
alert(data.result);
} else {
console.info(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>






Не совсем уверен в вашем случае, но для обходного пути вы можете справиться с этим с любым логическим флагом.
$('.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???
}
}
});
});
For some reason, it alerts it three times.
Вы привязываете click к .selection в каждой петле, и когда петля завершена, у вас есть 3 элемента с .selection, это означает, что вы связываете щелчок на всех трех из них.
Вы должны привязать его к 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 () {