Php+jquery+ajax Realizing paging

Source: Internet
Author: User
This article mainly introduces about Php+jquery+ajax realization paging, has a certain reference value, now share to everyone, the need for friends can refer to

Html

<div id= "List" >  <ul></ul> </div> <div id= "PageCount" ></div>

Css

#list {width:680px; height:530px; margin:2px auto; position:relative} #list ul li{float:left;width:220px; height:260px; MARGIN:2PX} #list ul Li img{width:220px, height:220px} #list ul li p{line-height:22px} #pagecount {width:500px; margin:10p x Auto; Text-align:center} #pagecount span{margin:4px, font-size:14px} #list ul li#loading{width:120px; height:32px; border : 1px solid #d3d3d3; Position:absolute; top:35%; left:42%; Text-align:center; Background: #f7f7f7 URL (loading.gif) no-repeat 8px 8px;-moz-box-shadow:1px 1px 2px rgba (0,0,0,.2); -webkit-box-shadow:1px 1px 2px Rgba (0,0,0,.2); box-shadow:1px 1px 2px Rgba (0,0,0,.2);}

Jquery

We declare the variables, and the following code uses the variables below.

var curpage = 1; Current page number Var total,pagesize,totalpage; Total records, number of displays per page, total pages

Next, we customize a function: GetData (), which is used to get the current page data. function, we use $.ajax () to send a post asynchronous request to the background pages.php, passing the current page number in JSON format to the background.

//Get Data Function GetData (page) {$.ajax ({type: ' POST ', url: ' pages.php ', data: {' P Agenum ':p age-1}, DataType: ' JSON ', Beforesend:function () {$ ("#list ul"). Append ("<li id= ' loading ' >loading ...  </li> ");//Display load animation}, Success:function (JSON) {$ (" #list ul "). empty ();//empty data area total = json.total;//overall record count PageSize = Json.pagesize; Show number of bars per page curpage = page; Current page totalpage = Json.totalpage;  Total pages var li = "";  var list = Json.list; $.each (List,function (Index,array) {//Traverse JSON data column Li + = "<li><a href= ' # ' >  "+array[' title '" + "</a></li>";  });  $ ("#list ul"). Append (LI);                      }, Complete:function () {//RAW ingredient page strip Getpagebar ();               When you click the paging link in the paging bar, call GetData (page) to load the data for the corresponding page number.        $ ("#pagecount span a"). On (' click ', function () {var rel = $ (this). attr ("rel");        if (rel) {getData (rel);    }          });  }, Error:function () {alert ("Data load Failed"); }  }); }

After the request succeeds and returns data, the corresponding data is appended to the variable, and the returned commodity data list is recycled to the corresponding container #list ul. When the data is fully loaded, call the paging bar function Getpagebar () raw page bar.

//get paging Bar function Getpagebar () {//page number greater than Max pages if (curpage>totalpage) curpage=  Totalpage;  Page number less than 1 if (curpage<1) curpage=1;     PAGESTR = "<span> Total" +total+ "bar </span><span>" +curpage + "/" +totalpage+ "</span>";  If it is the first page if (curpage==1) {pagestr + = "<span> home </span><span> prev </span>"; }else{Pagestr + = "<span><a href= ' javascript:void (0) ' rel= ' 1 ' > Home </a></span> <span><  A href= ' javascript:void (0) ' rel= ' "+ (curPage-1) +" ' > Prev </a></span> ";  }//If it is the last page if (curpage>=totalpage) {pagestr + = "<span> next </span><span> last </span>"; }else{Pagestr + = "<span><a href= ' javascript:void (0) ' rel= '" + (parseint (curpage) +1) + "> Next </a><  /span><span><a href= ' javascript:void (0) ' rel= ' "+totalpage+" ' > Last </a> </span> '; } $ ("#pagecount"). HTML (PAGESTR); }

Finally, when the page loads for the first time, we load the first page of data as GetData (1),

$ (function () {   getData (1);    });

Php

Pages.php receives AJAX requests for each front-end page, fetches data from the MySQL database based on the submitted page Pagenum value, calculates the total number of records and total pages, reads the list of data under the corresponding page number, and returns the final result in JSON format to the front page.

Include_once (' connect.php '); Connect the database, skip, please download source view     $page = intval ($_post[' pagenum '));//Current page    $result = mysql_query ("Select ID from Food"); $ Total = Mysql_num_rows ($result);///Record Count $pageSize = 6; Number of displays per page $totalPage = ceil ($total/$pageSize); Total pages    $startPage = $page * $pageSize;//start record//construct array $arr [' totals '] = $total; $arr [' pageSize '] = $pageSize; $arr [' Totalpa GE '] = $totalPage; $query = mysql_query ("Select Id,title,pic from the food Order by ID ASC limit  $startPage, $pageSize");//Querying paging data while ($row = Mysql_fetch_array ($query)) {  $arr [' list '] [] = array (' id ' = +  $row [' id '],  ' title ' = = $row [' title '],  ' pic ' = $row [' pic '],  ); } Echo Json_encode ($arr); Output JSON data

Finally, attach the MySQL table structure

CREATE TABLE IF not EXISTS ' food ' (  ' id ' int (one) not null auto_increment,   ' title ' varchar (+) ' NOT null  ', ' pic ' varchar (255) Not NULL,  PRIMARY KEY (' id ')) engine=myisam DEFAULT Charset=utf8;

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.