


Using 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?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?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.

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











Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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.
