search
HomeWeb Front-endJS TutorialHow 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

nbsp;html>

  
    <meta>
    <title></title>
    <link><!-- 换成自己的目录 -->
    <meta>
  
  <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>
  
   <p>
    </p><p>
     </p><p>
      </p><p>
       </p>
                                            
             

       

                                                                                             
书名作者出版日期平均分价格
                 

     

      

           

      

                                       

               

          <script></script>   <script></script>   <script> var partPageModule = ( function ( $ ) { var initPager = null,// 初始换分页函数 setPagerHTML = null,// 生成分的页HTML代码 pageClick = null,// 每一页按钮的点击事件 ajax = null, // ajax请求后台数据 renderButton = null, $content = $( &#39;&#39; ) // 动态生成的页码 ; /* 功能:完成初始化 * @totalPages 总页数,从后端获取 * @currentPage 当前所在的页数 */ initPager = function ( totalPages, currentPage ) { $content = setPagerHTML({ currentPage: currentPage, totalPages: totalPages, pageClick: PageClick }) $( &#39;#test&#39; ).empty().append( $content );// 得到分页后添加到#test $( &#39;#jumpToPage&#39; ).click( function ( e ) {// 绑定GO按钮的点击事件 e.preventDefault(); PageClick( totalPages, $(&#39;#page&#39;).val() * 1); }) $( &#39;#page&#39; ).keyup( function ( e ) {// Enter键绑定搜索事件 if ( e.keyCode === 13 ) { $( &#39;#jumpToPage&#39;).trigger( &#39;click&#39; ); } }) $( &#39;#result&#39; ).html( &#39;你点击的是第&#39; + currentPage + &#39;页&#39;) }; /* 功能:页码点击事件。重新生成所有页码,并且使用ajax获取数据 */ PageClick = function ( totalPages, currentPage ) { initPager( totalPages, currentPage ); ajax( currentPage );// 使用jsonp请求豆瓣 } ajax = function ( currentPage ) { var $input = $( &#39;#bookName&#39; ), bookName = &#39;&#39;, $tbody = $( &#39;#tbody&#39; ) // totalPages ; bookName = $input.val(); if ( !bookName ) { // 如果没有输入,就不要发送请求了 $input.focus(); return; } else { $.ajax({ type: &#39;get&#39;, url: &#39;https://api.douban.com/v2/book/search&#39;,// 豆瓣图书api dataType: &#39;jsonp&#39;, data: { q: bookName, start: ( parseInt( currentPage )-1 )*20 || 0 }, success: function ( data ) { var html = &#39;&#39;, books = data.books ; // totalPages = Math.ceil( data.total / data.count ); books.forEach( function ( value, index ) { html += &#39;<tr>&#39; + &#39;<td><a href="&#39; + value.alt + &#39;">&#39; + value.title + &#39;&#39; + &#39;<td>&#39; + value.author + &#39;&#39; + &#39;<td>&#39; + value.pubdate + &#39;&#39; + &#39;<td>&#39; + value.rating.average + &#39;&#39; + &#39;<td>&#39; + value.price + &#39;&#39; + &#39;&#39;; }) $tbody.html( html ); } }) } // return totalPages; } setPagerHTML = function ( options ) { var currentPage = options.currentPage, totalPages = options.totalPages, pageClick = options.pageClick, $content = $(&#39;<ul class="pagination">&#39;), startPage = 1, nextPage = currentPage + 1,//不需要考虑超出问题,后面有条件 prevPage = currentPage - 1 ; /* 逻辑处理,根据点击的不同的页生成不同的ul */ if ( currentPage == startPage ) {//当前页是起始页 $content.append( &#39;<li><span>首页&#39; ); // 首页不可用 $content.append( &#39;<li><span>上一页&#39; ); // 上一页不可用 } else { // 不是起始页 $content.append( renderButton( totalPages, 1, pageClick, &#39;首页&#39;) ); // 生成首页并绑定事件 $content.append( renderButton( totalPages, prevPage, pageClick, &#39;上一页&#39;) ); // 生成上一页并绑定事件 } if ( totalPages <=5 && currentPage <= 5 ) {// 总页数小于5,当前页小于5,全部生成页码 for ( var i = 1; i <= totalPages; i++ ) { if( i === currentPage ) { $content.append( &#39;<li class="active><span>&#39; + i + &#39;&#39; );// 当前页不可点击 } else { $content.append( renderButton( totalPages, i, pageClick, i) );// 其他页可以点击 } } } else if ( totalPages > 5 && totalPages - currentPage <= 2 ) {// 总页数大于5,当前页接近总页数,前面显示...,后面显示到结尾的页码 $content.append( &#39;<li><span>...&#39; ); for( var i = totalPages - 4; i <= totalPages; i++ ) { if ( i === currentPage ) { $content.append( &#39;<li class="active"><span>&#39; + i + &#39;&#39; ); } else { $content.append( renderButton( totalPages, i, pageClick, i) ); } } } else if ( totalPages > 5 && currentPage > 3) {// 总页数大于5,当前页在中间,前后生成...,生成中间页码 $content.append( &#39;<li><span>...&#39; ); for ( var i = currentPage - 2; i < currentPage + 2; i++ ) { if ( i === currentPage ) { $content.append( &#39;<li class="active"><span>&#39; + i + &#39;&#39; ); } else { $content.append( renderButton( totalPages, i ,pageClick, i) ); } } $content.append( &#39;<li><span>...&#39; ); } else if ( totalPages > 5 && currentPage <= 3 ) {// 总页数大于5,当前页接近第一页,显示前面页码,后面显示... for ( var i = 1; i <= 5; i++ ) { if ( i === currentPage ) { $content.append( &#39;<li class="active"><span>&#39; + i + &#39;&#39; ); } else { $content.append( renderButton( totalPages, i ,pageClick, i) ); } } $content.append( &#39;<li><span>...&#39; ); } if ( currentPage == totalPages ) {//当前页是末页 $content.append( &#39;<li><span>下一页&#39; ); // 下一页不可用 $content.append( &#39;<li><span>末页&#39; ); // 末页不可用 } else { // 不是起始页 $content.append( renderButton( totalPages, nextPage, pageClick, &#39;下一页&#39;) ); // 生成首页并绑定事件 $content.append( renderButton( totalPages, totalPages, pageClick, &#39;末页&#39;) ); // 生成上一页并绑定事件 } return $content; } renderButton = function ( totalPages, goPageIndex, eventHander, text ) { var $gotoPage = $( &#39;<li><a title="第&#39; + goPageIndex + &#39;页">&#39; + text + &#39;&#39; ); $gotoPage.click( function () { eventHander( totalPages, goPageIndex ); }) return $gotoPage; } return { init: initPager, ajax: ajax }  }(jQuery)) $( function () { $( &#39;#search&#39; ).click( function ( e ) { e.preventDefault(); var totalPage = partPageModule.ajax(1);// 由于ajax是异步的, totalPage = totalPage || 65;// 所以这个总页数是不准确的。一般这个数据是后端返回的。这里的65是javascript搜索的页数,不同的书籍搜索结果不一样,由于ajax异步执行,所以这里会默认为65。这里不是bug。 partPageModule.init( totalPage, 1 ); }) $( &#39;#bookName&#39; ).keyup( function ( e ) { if ( e.keyCode === 13 ) { $( &#39;#search&#39; ).trigger( &#39;click&#39; ); } }) $( &#39;#search&#39; ).trigger( &#39;click&#39; ); }) </script>   

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.