search
HomeWeb Front-endJS TutorialUsing jqGrid to read data and display it based on PHP and Mysql_jquery

jqGrid can dynamically read and load external data. This article will combine PHP and Mysql to explain how to use jqGrid to read and display data, as well as the ajax interaction process of querying data by entering keywords.

I will show you the renderings below. Friends who like it can read the full text.

jqGrid itself has search and edit table modules, but these modules will make the entire plug-in a bit bulky, and I think jqGrid’s search query and edit/add functions are not easy to use, so I gave up jqGrid’s own search and edit functions. The edit table module uses the jquery tool to complete related functions, which is in line with the actual application of the project.

XHTML

<div id="opt"> 
 <div id="query"> 
 <label>编号:</label><input type="text" class="input" id="sn" /> 
 <label>名称:</label><input type="text" class="input" id="title" /> 
 <input type="submit" class="btn" id="find_btn" value="查 询" /> 
 </div> 
 <input type="button" class="btn" id="add_btn" value="新 增" /> 
 <input type="button" class="btn" id="del_btn" value="删 除" /> 
</div> 
<table id="list"></table> 
<div id="pager"></div> 

We are creating two input boxes for querying the number and name, as well as the "Add" and "Delete" buttons. The add and delete functions will be specifically explained in the following article. In addition, there is a #list for placing tables (jqGrid generates tables) and a paging bar #pager in xhtml.

Javascript

First call jqGrid. We take the data in the article jqGrid: Application of Powerful Table Plug-in on this website as an example to call jqGrid to generate a table. Please see the code and comments.

$("#list").jqGrid({ 
 url:'do.php&#63;action=list', //请求数据的url地址 
 datatype: "json", //请求的数据类型 
 colNames:['编号','名称','主屏尺寸','操作系统','电池容量', '价格(¥)','操作'], //数据列名称(数组) 
 colModel:[ //数据列各参数信息设置 
  {name:'sn',index:'sn', editable:true, width:80,align:'center', title:false}, 
  {name:'title',index:'title', width:180, title:false}, 
  {name:'size',index:'size', width:120}, 
 {name:'os',index:'os', width:120}, 
  {name:'charge',index:'charge', width:100,align:'center'}, 
 {name:'price',index:'price', width:80,align:'center'}, 
  {name:'opt',index:'opt', width:80, sortable:false, align:'center'}  
 ], 
 rowNum:10, //每页显示记录数 
 rowList:[10,20,30], //分页选项,可以下拉选择每页显示记录数 
 pager: '#pager', //表格数据关联的分页条,html元素 
 autowidth: true, //自动匹配宽度 
 height:275, //设置高度 
 gridview:true, //加速显示 
 viewrecords: true, //显示总记录数 
 multiselect: true, //可多选,出现多选框 
 multiselectWidth: 25, //设置多选列宽度 
 sortable:true, //可以排序 
 sortname: 'id', //排序字段名 
 sortorder: "desc", //排序方式:倒序,本例中设置默认按id倒序排序 
 loadComplete:function(data){ //完成服务器请求后,回调函数 
 if(data.records==0){ //如果没有记录返回,追加提示信息,删除按钮不可用 
  $("p").appendTo($("#list")).addClass("nodata").html('找不到相关数据!'); 
  $("#del_btn").attr("disabled",true); 
 }else{ //否则,删除提示,删除按钮可用 
  $("p.nodata").remove(); 
  $("#del_btn").removeAttr("disabled"); 
 } 
 } 
}); 

For jqGrid related option settings, please refer to: jqGrid Chinese documentation - option settings .

In addition, when we click the "Query" button, a query keyword request is sent to the background PHP program, and jqGrid responds based on the results returned by the server. Please see the code.

$(function(){ 
 $("#find_btn").click(function(){ 
 var title = escape($("#title").val()); 
 var sn = escape($("#sn").val()); 
 $("#list").jqGrid('setGridParam',{ 
  url:"do.php&#63;action=list", 
  postData:{'title':title,'sn':sn}, //发送数据 
  page:1 
 }).trigger("reloadGrid"); //重新载入 
 }); 
}); 

PHP

In the previous two pieces of JS code, you can see that the background url addresses for reading lists and querying business requests are do.php?action=list. The background php code is responsible for querying the data in the mysql data table according to conditions. And return the data to the front-end jqGrid in JSON format, please see the php code:

include_once ("connect.php"); 
$action = $_GET['action']; 
switch ($action) { 
 case 'list' : //列表 
 $page = $_GET['page']; //获取请求的页数 
 $limit = $_GET['rows']; //获取每页显示记录数 
 $sidx = $_GET['sidx']; //获取默认排序字段 
 $sord = $_GET['sord']; //获取排序方式 
 if (!$sidx) 
  $sidx = 1; 
 
 $where = ''; 
 $title = uniDecode($_GET['title'],'utf-8'); //获取查询关键字:名称 
 if(!empty($title)) 
  $where .= " and title like '%".$title."%'"; 
 $sn = uniDecode($_GET['sn'],'utf-8'); //获取查询关键字:编号 
 if(!empty($sn)) 
  $where .= " and sn='$sn'"; 
 //执行SQL 
 $result = mysql_query("SELECT COUNT(*) AS count FROM products where deleted=0".$where); 
 $row = mysql_fetch_array($result, MYSQL_ASSOC); 
 $count = $row['count']; //获取总记录数 
 //根据记录数分页 
 if ($count > 0) { 
  $total_pages = ceil($count / $limit); 
 } else { 
  $total_pages = 0; 
 } 
 if ($page > $total_pages) 
  $page = $total_pages; 
 $start = $limit * $page - $limit; 
 if ($start < 0 ) $start = 0; 
 //执行分页SQL 
 $SQL = "SELECT * FROM products WHERE deleted=0".$where." ORDER BY $sidx $sord 
 LIMIT $start , $limit"; 
 $result = mysql_query($SQL) or die("Couldn t execute query." . mysql_error()); 
 $responce->page = $page; //当前页 
 $responce->total = $total_pages; //总页数 
 $responce->records = $count; //总记录数 
 $i = 0; 
 //循环读取数据 
 while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
  $responce->rows[$i]['id'] = $row[id]; 
  $opt = "<a href='edit.php'>修改</a>"; 
  $responce->rows[$i]['cell'] = array ( 
  $row['sn'], 
  $row['title'], 
  $row['size'], 
  $row['os'], 
  $row['charge'], 
  $row['price'], 
  $opt 
  ); 
  $i++; 
 } 
 echo json_encode($responce); //输出JSON数据 
 break; 
 case '' : 
 echo 'Bad request.'; 
 break; 
} 

It is worth mentioning that when we perform Chinese queries, that is, when entering Chinese keywords for query, we need to use js for escape encoding, and then php will decode accordingly when receiving the Chinese keywords, otherwise the Chinese will not be recognized. String phenomenon, in this example, the uniDecode function is used to decode, and the code is provided together:

/处理接收jqGrid提交查询的中文字符串 
function uniDecode($str, $charcode) { 
 $text = preg_replace_callback("/%u[0-9A-Za-z]{4}/", toUtf8, $str); 
 return mb_convert_encoding($text, $charcode, 'utf-8'); 
} 
function toUtf8($ar) { 
 foreach ($ar as $val) { 
 $val = intval(substr($val, 2), 16); 
 if ($val < 0x7F) { // 0000-007F 
  $c .= chr($val); 
 } 
 elseif ($val < 0x800) { // 0080-0800 
  $c .= chr(0xC0 | ($val / 64)); 
  $c .= chr(0x80 | ($val % 64)); 
 } else { // 0800-FFFF 
  $c .= chr(0xE0 | (($val / 64) / 64)); 
  $c .= chr(0x80 | (($val / 64) % 64)); 
  $c .= chr(0x80 | ($val % 64)); 
 } 
 } 
 return $c; 
} 

The above is what this article introduces to you using jqGrid to read and display data based on the combination of PHP and Mysql. We will continue to introduce jqgrid table-related applications to you, so stay tuned.

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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment