修复YouTube API数据分页v3

时间:2018-11-05 22:16:41

标签: javascript search pagination youtube youtube-api

到目前为止,我的YouTube api数据v3搜索脚本运行良好,但由于此脚本困扰我很多天,我认为即时盲目的它会起作用,并且每2次输入都会分页。但是在js或html代码中一定有一个失败应该很容易,但是我想不通,请帮助我。演示链接在 Artist search Battle Rap Net Youtube Search

到目前为止,这是我使用的代码,请查看演示链接以了解问题。

Js代码:

    var nextPageToken, prevPageToken;
var firstPage=true;
$(document).ready(function()
{

    $('#searchbutton').click(function()
    {
        // Called automatically when JavaScript client library is loaded.
      //  alert('i am clicked');
        gapi.client.load('youtube', 'v3', onYouTubeApiLoad);

        // Called automatically when YouTube API interface is loaded .


        // Called automatically with the response of the YouTube API request.


          // $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page</button></div>");
           //  $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page"+nextPageToken+"</button></div>");

        });
  $('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page "+prevPageToken+"</button></div>");
    $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page "+nextPageToken+"</button></div>");

     $('#nextPageButton').click(function()
    {
       // alert('i am clicked');
        console.log(nextPageToken);
        searchYouTubeApi(nextPageToken);
    });

     $('#prevPageButton').click(function()
    {
       // alert('i am clicked');
        console.log(prevPageToken);
        searchYouTubeApi(prevPageToken);
    });

});

 function onYouTubeApiLoad() 
        {
            // See to get a key for your own applications.
            gapi.client.setApiKey('MYAPICODE');
            searchYouTubeApi();

        }

        function searchYouTubeApi(PageToken)
        {
             var searchText= $('#searchtext').val();
             //$('#response').append("<div id=\"searching\"><b>Searching for "+searchText+"</b></div>");
          $('#response').replaceWith("<div id=\"searching\"><b>Searching for "+searchText+"</b></div>");

            // Use the JavaScript client library to create a search.list() API call to Youtube's "Search" resource
            var request = gapi.client.youtube.search.list(
            {
            part: 'snippet',
            q:searchText,
            maxResults:2,
            pageToken:PageToken
            });

            // Send the request to the API server,
            // and invoke onSearchRepsonse() with the response.
            request.execute(onSearchResponse);
           //  $('#response').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page return from request execute method is: "+nextPageToken+"</button></div>");
        }

        function onSearchResponse(response) 
        {

            var responseString = JSON.stringify(response, '', 2);
            var resultCount = response.pageInfo.totalResults;
                nextPageToken=response.nextPageToken;
                prevPageToken=response.prevPageToken;
              // document.getElementById('response').innerHTML += responseString;
                //$('#response').append("<div id=count><b>Found "+resultCount+" Results.</b></div>");
            $('#count').replaceWith("<div id=count><b>Found "+resultCount+" Results.</b></div>");
          //$('#searching').append("<div id=length><b>Length "+response.items.length+" </b></div>");


            for (var i=0; i<response.items.length;i++)
            {
                //store each JSON value in a variable
                var publishedAt=response.items[i].snippet.publishedAt;
                var channelId=response.items[i].snippet.channelId;
                var title=response.items[i].snippet.title;
                var description=response.items[i].snippet.description;
                var thumbnails_default=response.items[i].snippet.thumbnails.default.url;
                var thumbnails_medium=response.items[i].snippet.thumbnails.medium.url;
                var thumbnails_high=response.items[i].snippet.thumbnails.high.url;
                var channelTitle=response.items[i].snippet.channelTitle;
                var liveBroadcastContent=response.items[i].snippet.liveBroadcastContent;
                var videoID=response.items[i].id.videoId;
                 //var firstPage=true;

              //  console.log(thumbnails_default);
                //A HTTP call to this URL with videoID will give all XML info of that video: 
                //http://gdata.youtube.com/feeds/api/videos?q=videoID
              //  console.log(videoID);

                //replace the first search button with a 'more' button
                //$('button').replaceWith("<button type='button' id=More"+i+">More...</button>");

                if(firstPage===true)
               {
               //print the stored variables in a div element
                $('#snipp').append("<div id=T><b>Title:</b> "+title+"</div><div id=C><b>Channel ID: </b>"+channelId+"</div><div id=D><b>Description </b>"+description+"</div><div id=P><b>Published on: </b>"+publishedAt+"</div><div id=CT><b>Channel Title: </b>"+channelTitle+"</div><a id=linktoVid href='http://www.youtube.com/watch?v="+videoID+"'><img id=imgTD src=\""+thumbnails_default+"\"/></a><br/><br/><a id=linktoVid1 href='http://www.youtube.com/watch?v="+videoID+"'><video id=vidTD width=\"320\" height=\"240\" controls poster="+thumbnails_default+"><source src='http://www.youtube.com/watch?v="+videoID+">Your browser does not support the video tag.</video></a><br/><br/>");

                }
                else
                {
                  $('#T').replaceWith("<div id=T><b>Title:</b> "+title+"</div>");
                  $('#C').replaceWith("<div id=C><b>Channel ID: </b>"+channelId+"</div>");
                  $('#D').replaceWith("<div id=D><b>Description </b>"+description+"</div>");
                  $('#P').replaceWith("<div id=P><b>Published on: </b>"+publishedAt+"</div>");
                  $('#CT').replaceWith("<div id=CT><b>Channel Title: </b>"+channelTitle+"</div>");
                  $('#linktoVid').replaceWith("<a id=linktoVid href='http://www.youtube.com/watch v="+videoID+"'><img id=imgTD src=\""+thumbnails_default+"\"/></a><br/><br/><a id=linktoVid1 href='http://www.youtube.com/watch?v="+videoID+"'><video id=vidTD width=\"320\" height=\"240\" controls poster="+thumbnails_default+"><source src='http://www.youtube.com/watch?v="+videoID+">Your browser does not support the video tag.</video></a><br/><br/>");
                }

            //  $('#snipp').append("<div id=C"+i+">Channle ID: "+channelId+"</div><br/>");

            //link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=76TlUlPZQfQ&amp;feature=youtube_gdata'/>


            }
             // $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\" onclick=\"alert('Hello world!')\">Next Page "+nextPageToken+"</button></div>");
             // return nextPageToken;
             firstPage=false;
        }

HTML:

<body>



      <div id="search">
      <input type="text"  value="eureka" id="searchtext"><button type="button" id="searchbutton">Find</button>
      </div>
        <button type="button">Search Me...</button>

        <pre id="response">
        </pre>
      <pre id="count"></pre>
        <pre class="vID"></pre>
       <div id="snipp">
          <div id=T0
        </div>
        <br/><br/><br/>

    </body>

1 个答案:

答案 0 :(得分:0)

用您的代码创建jsfiddle后,我可以检查分页是否正常工作。

您面临的问题在于您的HTML代码(最具体的是:您如何构建HTML代码)

我的卑鄙建议是“而不是使用append” ,而是重新创建呈现当前页面的HTML。

此外,在屏幕上加载所有控件之后,“ prevPageButton”和“ nextPageButton”按钮将显示undefined

在这种情况下,请更改以下行:

$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page " + prevPageToken + "</button></div>");
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page " + nextPageToken + "</button></div>");

为此:

if (prevPageToken == undefined) {
    $('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page</button></div>");
} else {
    $('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page " + prevPageToken + "</button></div>");
}    

if (nextPageToken == undefined) {
    $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page</button></div>");
} else {
    $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page " + nextPageToken + "</button></div>");
}

进行一些修改后,您可以在此处检查updated and working jsfiddle


tl; dr版本如下:

  • 用于构建HTML代码的逻辑已替换为设置(在for循环中)用于构建HTML代码的变量。
  • 循环结束时,HTML被直接添加到名为“ snipp”的div容器中。
  • 删除了其他不必要的HTML代码。

这是修改后的代码:

HTML:

<div id="search">
  <input type="text" value="eureka" id="searchtext"><button type="button" id="searchbutton">Find</button>
</div>
<button type="button">Search Me...</button>
<pre id="response">
        </pre>
<pre id="count"></pre>
<pre class="vID"></pre>
<div id="snipp"></div>

JS:

function onSearchResponse(response) {

  var responseString = JSON.stringify(response, '', 2);
  var resultCount = response.pageInfo.totalResults;
  nextPageToken = response.nextPageToken;
  prevPageToken = response.prevPageToken;
  $('#count').replaceWith("<div id=count><b>Found " + resultCount + " Results.</b></div>");

  // This variable will save the HTML code in construction.
  var HTML_CONTENT = "";

  for (var i = 0; i < response.items.length; i++) {
    //store each JSON value in a variable
    var publishedAt = response.items[i].snippet.publishedAt;
    var channelId = response.items[i].snippet.channelId;
    var title = response.items[i].snippet.title;
    var description = response.items[i].snippet.description;
    var thumbnails_default = response.items[i].snippet.thumbnails.default.url;
    var thumbnails_medium = response.items[i].snippet.thumbnails.medium.url;
    var thumbnails_high = response.items[i].snippet.thumbnails.high.url;
    var channelTitle = response.items[i].snippet.channelTitle;
    var liveBroadcastContent = response.items[i].snippet.liveBroadcastContent;
    var videoID = response.items[i].id.videoId;

    // Buld the HTML to render at the current page.
    HTML_CONTENT += "<div id='video_item'> " +
      " <div id=T><b>Title:</b>" + title + "</div> " +
      " <div id=C><b>Channel ID: </b>" + channelId + "</div> " +
      " <div id=D><b>Description </b>" + description + "</div> " +
      " <div id=P><b>Published on: </b>" + publishedAt + "</div> " +
      " <div id=CT><b>Channel Title: </b>" + channelTitle + "</div> " +
      " <a id='linktoVid' href='http://www.youtube.com/watch?v=" + videoID + "'><img id='imgTD' src='" + thumbnails_default + "' /></a><br/><br/><a id='linktoVid1' href='http://www.youtube.com/watch?v=" + videoID + "'><video id='vidTD' width=\"320\" height=\"240\" controls poster='" + thumbnails_default + "'><source src='http://www.youtube.com/watch?v=" + videoID + "'>Your browser does not support the video tag.</video></a><br/><br/> " +
      "</div>";
  }

  // Post all HTML generated code (built in the previous for-loop).
  document.getElementById('snipp').innerHTML = HTML_CONTENT;

  // $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\" onclick=\"alert('Hello world!')\">Next Page "+nextPageToken+"</button></div>");
  // return nextPageToken;
  firstPage = false;
}