javascript - 修复Youtube API数据分页v3

标签 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>

最佳答案

用您的代码创建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;
    }
    

    关于javascript - 修复Youtube API数据分页v3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53163030/

    相关文章:

    javascript - 重置功能,或者可能停止某些功能并重新启动它?

    python - 在 Django 中对分页 View 的第一页使用缓存

    javascript - SetInterval/Slider 不适用于 Chrome

    javascript - TabPanel 选项卡上的 itemId 被框架设置为 "deleted"?

    java - 在 Activity 负载上实现搜索栏

    javascript - 如何在 meteor 待办事项应用程序示例中添加搜索

    asp.net - 分页GridView

    javascript - 使用 Ajax 传递参数(使用延迟和 promise )需要帮助

    javascript - 如何像Medium一样进行拖放?

    c++ - 计算搜索比较 C++