


How to implement paging using ajax combined with Douban search (code attached)
This time I will show you how to implement ajax combined with Douban search for paging (with code), and what are the precautions for implementing ajax combined with Douban search for paging . The following is a practical case, let’s take a look. .
Use Douban API to get paginated results. Equivalent to the results obtained from the backend database. The difference is that there is no way to know the number of pages in advance. Although the total page count can be obtained by requesting the API, since Ajax is asynchronous, it does not make sense to give the total page count at the beginning of pagination. I used a fixed total page count of 65 (exactly the total number of pages returned by searching for javascript books). Therefore, other books are not 65 pages. There will be more or less pages. This is not a bug.
Features
1. There is no need to touch the backend in the whole process, the front-end can be independent (I have been looking for a complete example for a long time).
2. Use bootstrap’s pagination to create page numbers and panel to create a panel for placing results.
The code is as follows
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="css/bootstrap.css" /><!-- 换成自己的目录 --> <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" /> </head> <style> .pagination> li > a { cursor: pointer; } .pagination > li > span { margin-left: 0; color: #ccc; background-color: transparent; cursor: default; } .pagination > li > span:hover { color: #ccc; background-color: transparent; cursor: default; } .m20 { margin: 20px 0; } </style> <body> <p class="container-fluid"> <p class="col-md-12"> <p class="panel panel-default"> <p class="panel-heading"> <form class="input-group"> <input type="text" value="javascript" class="form-control" id="bookName" placeholder="请输入书名" required="required"/> <span class="input-group-btn"> <button class="btn" id="search">搜索</button> </span> </form> </p> <p class="panel-body"> <table class="table table-bordered"> <thead> <th>书名</th> <th>作者</th> <th>出版日期</th> <th>平均分</th> <th>价格</th> </thead> <tbody id="tbody"> </tbody> </table> </p> </p> <p class="row"> <p class="col-md-6"> <p id="test"></p> </p> <p class="col-md-4"> <p class="input-group m20"><!-- 保持与#test中的.pagination对齐 --> <input type="text" class="form-control" id="page"/> <span class="input-group-btn"> <button class="btn btn-default" id="jumpToPage">GO</button> </span> </p> </p> </p> <p id="result" class="alert alert-info"></p> </p> </p> <script type="text/javascript" src="js/jquery-1.11.2.min.js" ></script> <!-- 换成自己的目录 --> <script type="text/javascript" src="js/bootstrap.js" ></script> <!-- 换成自己的目录 --> <script type="text/javascript"> var partPageModule = ( function ( $ ) { var initPager = null,// 初始换分页函数 setPagerHTML = null,// 生成分的页HTML代码 pageClick = null,// 每一页按钮的点击事件 ajax = null, // ajax请求后台数据 renderButton = null, $content = $( '' ) // 动态生成的页码 ; /* 功能:完成初始化 * @totalPages 总页数,从后端获取 * @currentPage 当前所在的页数 */ initPager = function ( totalPages, currentPage ) { $content = setPagerHTML({ currentPage: currentPage, totalPages: totalPages, pageClick: PageClick }) $( '#test' ).empty().append( $content );// 得到分页后添加到#test $( '#jumpToPage' ).click( function ( e ) {// 绑定GO按钮的点击事件 e.preventDefault(); PageClick( totalPages, $('#page').val() * 1); }) $( '#page' ).keyup( function ( e ) {// Enter键绑定搜索事件 if ( e.keyCode === 13 ) { $( '#jumpToPage').trigger( 'click' ); } }) $( '#result' ).html( '你点击的是第' + currentPage + '页') }; /* 功能:页码点击事件。重新生成所有页码,并且使用ajax获取数据 */ PageClick = function ( totalPages, currentPage ) { initPager( totalPages, currentPage ); ajax( currentPage );// 使用jsonp请求豆瓣 } ajax = function ( currentPage ) { var $input = $( '#bookName' ), bookName = '', $tbody = $( '#tbody' ) // totalPages ; bookName = $input.val(); if ( !bookName ) { // 如果没有输入,就不要发送请求了 $input.focus(); return; } else { $.ajax({ type: 'get', url: 'https://api.douban.com/v2/book/search',// 豆瓣图书api dataType: 'jsonp', data: { q: bookName, start: ( parseInt( currentPage )-1 )*20 || 0 }, success: function ( data ) { var html = '', books = data.books ; // totalPages = Math.ceil( data.total / data.count ); books.forEach( function ( value, index ) { html += '<tr>' + '<td><a href="' + value.alt + '">' + value.title + '</a></td>' + '<td>' + value.author + '</td>' + '<td>' + value.pubdate + '</td>' + '<td>' + value.rating.average + '</td>' + '<td>' + value.price + '</td>' + '</tr>'; }) $tbody.html( html ); } }) } // return totalPages; } setPagerHTML = function ( options ) { var currentPage = options.currentPage, totalPages = options.totalPages, pageClick = options.pageClick, $content = $('<ul class="pagination"></ul>'), startPage = 1, nextPage = currentPage + 1,//不需要考虑超出问题,后面有条件 prevPage = currentPage - 1 ; /* 逻辑处理,根据点击的不同的页生成不同的ul */ if ( currentPage == startPage ) {//当前页是起始页 $content.append( '<li><span>首页</span></li>' ); // 首页不可用 $content.append( '<li><span>上一页</span></li>' ); // 上一页不可用 } else { // 不是起始页 $content.append( renderButton( totalPages, 1, pageClick, '首页') ); // 生成首页并绑定事件 $content.append( renderButton( totalPages, prevPage, pageClick, '上一页') ); // 生成上一页并绑定事件 } if ( totalPages <=5 && currentPage <= 5 ) {// 总页数小于5,当前页小于5,全部生成页码 for ( var i = 1; i <= totalPages; i++ ) { if( i === currentPage ) { $content.append( '<li class="active><span>' + i + '</span></li>' );// 当前页不可点击 } else { $content.append( renderButton( totalPages, i, pageClick, i) );// 其他页可以点击 } } } else if ( totalPages > 5 && totalPages - currentPage <= 2 ) {// 总页数大于5,当前页接近总页数,前面显示...,后面显示到结尾的页码 $content.append( '<li><span>...</span></li>' ); for( var i = totalPages - 4; i <= totalPages; i++ ) { if ( i === currentPage ) { $content.append( '<li class="active"><span>' + i + '</span></li>' ); } else { $content.append( renderButton( totalPages, i, pageClick, i) ); } } } else if ( totalPages > 5 && currentPage > 3) {// 总页数大于5,当前页在中间,前后生成...,生成中间页码 $content.append( '<li><span>...</span></li>' ); for ( var i = currentPage - 2; i < currentPage + 2; i++ ) { if ( i === currentPage ) { $content.append( '<li class="active"><span>' + i + '</span></li>' ); } else { $content.append( renderButton( totalPages, i ,pageClick, i) ); } } $content.append( '<li><span>...</span></li>' ); } else if ( totalPages > 5 && currentPage <= 3 ) {// 总页数大于5,当前页接近第一页,显示前面页码,后面显示... for ( var i = 1; i <= 5; i++ ) { if ( i === currentPage ) { $content.append( '<li class="active"><span>' + i + '</span></li>' ); } else { $content.append( renderButton( totalPages, i ,pageClick, i) ); } } $content.append( '<li><span>...</span></li>' ); } if ( currentPage == totalPages ) {//当前页是末页 $content.append( '<li><span>下一页</span></li>' ); // 下一页不可用 $content.append( '<li><span>末页</span></li>' ); // 末页不可用 } else { // 不是起始页 $content.append( renderButton( totalPages, nextPage, pageClick, '下一页') ); // 生成首页并绑定事件 $content.append( renderButton( totalPages, totalPages, pageClick, '末页') ); // 生成上一页并绑定事件 } return $content; } renderButton = function ( totalPages, goPageIndex, eventHander, text ) { var $gotoPage = $( '<li><a title="第' + goPageIndex + '页">' + text + '</a></li>' ); $gotoPage.click( function () { eventHander( totalPages, goPageIndex ); }) return $gotoPage; } return { init: initPager, ajax: ajax } }(jQuery)) $( function () { $( '#search' ).click( function ( e ) { e.preventDefault(); var totalPage = partPageModule.ajax(1);// 由于ajax是异步的, totalPage = totalPage || 65;// 所以这个总页数是不准确的。一般这个数据是后端返回的。这里的65是javascript搜索的页数,不同的书籍搜索结果不一样,由于ajax异步执行,所以这里会默认为65。这里不是bug。 partPageModule.init( totalPage, 1 ); }) $( '#bookName' ).keyup( function ( e ) { if ( e.keyCode === 13 ) { $( '#search' ).trigger( 'click' ); } }) $( '#search' ).trigger( 'click' ); }) </script> </body> </html> <!-- https://api.douban.com/v2/book/search --> <!-- 参数 意义 备注 q 查询关键字 q和tag必传其一 tag 查询的tag q和tag必传其一 start 取结果的offset 默认为0 count 取结果的条数 默认为20,最大为100 -->
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How does ajax submit a form and implement file upload
Ajax transmits json format data to the background. How to handle errors
The above is the detailed content of How to implement paging using ajax combined with Douban search (code attached). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How does Xianyu search for users? In the software Xianyu, we can directly find the users we want to communicate with in the software. But I don’t know how to search for users. Just view it among the users after searching. Next is the introduction that the editor brings to users about how to search for users. If you are interested, come and take a look! How to search for users in Xianyu? Answer: View details among the searched users. Introduction: 1. Enter the software and click on the search box. 2. Enter the user name and click Search. 3. Select [User] under the search box to find the corresponding user.

How to use Baidu Advanced Search Baidu search engine is currently one of the most commonly used search engines in China. It provides a wealth of search functions, one of which is advanced search. Advanced search can help users search for the information they need more accurately and improve search efficiency. So, how to use Baidu advanced search? The first step is to open the Baidu search engine homepage. First, we need to open Baidu’s official website, which is www.baidu.com. This is the entrance to Baidu search. In the second step, click the Advanced Search button. On the right side of the Baidu search box, there is

In the era dominated by intelligence, office software has also become popular, and Wps forms are adopted by the majority of office workers due to their flexibility. At work, we are required not only to learn simple form making and text entry, but also to master more operational skills in order to complete the tasks in actual work. Reports with data and using forms are more convenient, clear and accurate. The lesson we bring to you today is: The WPS table cannot find the data you are searching for. Why please check the search option location? 1. First select the Excel table and double-click to open it. Then in this interface, select all cells. 2. Then in this interface, click the "Edit" option in "File" in the top toolbar. 3. Secondly, in this interface, click "

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

The mobile Taobao app software provides a lot of good products. You can buy them anytime and anywhere, and everything is genuine. The price tag of each product is clear. There are no complicated operations at all, making you enjoy more convenient shopping. . You can search and purchase freely as you like. The product sections of different categories are all open. Add your personal delivery address and contact number to facilitate the courier company to contact you, and check the latest logistics trends in real time. Then some new users are using it for the first time. If you don’t know how to search for products, of course you only need to enter keywords in the search bar to find all the product results. You can’t stop shopping freely. Now the editor will provide detailed online methods for mobile Taobao users to search for store names. 1. First open the Taobao app on your mobile phone,

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make
