0

如何使用 jqGrid 的单一搜索功能?

我遵循“3.7 版中的新功能”下的示例“单一搜索”。jqGrid 演示页面

我的脚本几乎完全保存了用于从数据库中检索数据的查询,但我的脚本不进行过滤。

谁能指出我使用 PHP 的单一搜索功能的完整示例?

我对演示页面中的脚本也有疑问。

  1. jQuery如何将条件传递给PHP来过滤结果?我在查询中注意到它有一个变量$where,但该变量没有在 PHP 脚本中声明。
4

1 回答 1

3

我已经使用 MySQL 数据库编写了一个示例。
首先创建一个“test”数据库,一个“items”表,并插入一些记录:

CREATE DATABASE IF NOT EXISTS test;

CREATE TABLE IF NOT EXISTS `items` (
  `item_id` int(11) NOT NULL,
  `item` varchar(255) DEFAULT '',
  `item_cd` varchar(255) DEFAULT '',
  PRIMARY KEY (`item_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

LOCK TABLES `items` WRITE;
INSERT INTO `items` VALUES (1,'Lorem','575878');
INSERT INTO `items` VALUES (2,'Lorem','857450');
INSERT INTO `items` VALUES (3,'ipsum','292404');
INSERT INTO `items` VALUES (4,'dolor','814131');
INSERT INTO `items` VALUES (5,'sit','962077');
INSERT INTO `items` VALUES (6,'amet,','549801');
INSERT INTO `items` VALUES (7,'sed','166822');
INSERT INTO `items` VALUES (8,'in','616758');
INSERT INTO `items` VALUES (9,'id','550799');
INSERT INTO `items` VALUES (10,'dictum','763004');
INSERT INTO `items` VALUES (11,'velit','244985');
INSERT INTO `items` VALUES (12,'est','525127');
INSERT INTO `items` VALUES (13,'suspendisse,','351690');
INSERT INTO `items` VALUES (14,'mauris','655061');
INSERT INTO `items` VALUES (15,'eget','423779');
INSERT INTO `items` VALUES (16,'imperdiet','493615');
INSERT INTO `items` VALUES (17,'ut,','864029');
INSERT INTO `items` VALUES (18,'mauris','546065');
INSERT INTO `items` VALUES (19,'vestibulum,','562819');
INSERT INTO `items` VALUES (20,'sagittis','238043');
INSERT INTO `items` VALUES (21,'ac.','867508');
INSERT INTO `items` VALUES (22,'Mauris','674897');
INSERT INTO `items` VALUES (23,'id','288097');
INSERT INTO `items` VALUES (24,'quam,','889530');
UNLOCK TABLES;

接下来,创建 html 页面“singlesearch.html”:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" media="screen" href="http://www.trirand.com/blog/jqgrid/themes/redmond/jquery-ui-custom.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="http://www.trirand.com/blog/jqgrid/themes/ui.jqgrid.css" />
    <script src="http://www.trirand.com/blog/jqgrid/js/jquery.js" type="text/javascript"></script>
    <script src="http://www.trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
    <script src="http://www.trirand.com/blog/jqgrid/js/jquery.jqGrid.js" type="text/javascript"></script>
    <script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery("#single").jqGrid({
            url:'localset.php',
            datatype: "json",
            height: 255,
            width: 600,
            colNames:['Index','Name', 'Code'],
            colModel:[
                {name:'item_id',index:'item_id', width:65, sorttype:'int'},
                {name:'item'   ,index:'item'   , width:150},
                {name:'item_cd',index:'item_cd', width:100}
            ],
            rowNum:50,
            rowTotal: 2000,
            rowList : [20,30,50],
            loadonce: false,
            mtype: "GET",
            rownumbers: true,
            rownumWidth: 40,
            gridview: true,
            pager: '#psingle',
            sortname: 'item_id',
            viewrecords: true,
            sortorder: "asc",
            caption: "Single search on local data",
            loadError: function(jqXHR, textStatus, errorThrown) {
                /*
                alert('HTTP status code: ' + jqXHR.status + '\n' +
                      'textStatus: ' + textStatus + '\n' +
                      'errorThrown: ' + errorThrown);
                alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
                */
                alert(jqXHR.responseText);
            }
        });

        jQuery("#single").jqGrid(
            'navGrid',
            '#psingle',
            {del:false,add:false,edit:false},
            {},                        // default settings for edit
            {},                        // default settings for add
            {},                        // 
            {closeAfterSearch:true},   // search options
            {}                         // view parameters
        );
    });
    </script>
</head>
<body>
    <table id="single"></table>
    <div id="psingle"></div>
</body>
</html>

然后创建一个 PHP 页面“localset.php”:

<?php

function myTrace($str) {
    // Adjust the log file name before uncommenting
    //@file_put_contents("/tmp/localset.log", $str."\n", FILE_APPEND);
}

myTrace(print_r($_REQUEST,true));

// connect to the database
$link = mysqli_init();

// Adjust host, user, password and dbname before use!
$db = mysqli_real_connect($link, "myhost", "myuser", "mypass", "test");
if (!$db) {
    die('Connect Error ('.mysqli_connect_errno().'): '.mysqli_connect_error());
}

mysqli_set_charset($link, "utf8");

$page  = isset($_REQUEST['page']) ? $_REQUEST['page'] : 0;          // get the requested page
$limit = isset($_REQUEST['rows']) ? $_REQUEST['rows'] : 50;         // get how many rows we want to have into the grid
$sidx  = isset($_REQUEST['sidx']) ? $_REQUEST['sidx'] : 1;          // get index row - i.e. user click to sort
$sord  = isset($_REQUEST['sord']) ? $_REQUEST['sord'] : "asc";      // get the direction

if ($_REQUEST["_search"] == "false") {
    $where = "where 1";
} else {
    $operations = array(
        'eq' => "= '%s'",            // Equal
        'ne' => "<> '%s'",           // Not equal
        'lt' => "< '%s'",            // Less than
        'le' => "<= '%s'",           // Less than or equal
        'gt' => "> '%s'",            // Greater than
        'ge' => ">= '%s'",           // Greater or equal
        'bw' => "like '%s%%'",       // Begins With
        'bn' => "not like '%s%%'",   // Does not begin with
        'in' => "in ('%s')",         // In
        'ni' => "not in ('%s')",     // Not in
        'ew' => "like '%%%s'",       // Ends with
        'en' => "not like '%%%s'",   // Does not end with
        'cn' => "like '%%%s%%'",     // Contains
        'nc' => "not like '%%%s%%'", // Does not contain
        'nu' => "is null",           // Is null
        'nn' => "is not null"        // Is not null
    ); 
    $value = mysqli_real_escape_string($link, $_REQUEST["searchString"]);
    $where = sprintf("where %s ".$operations[$_REQUEST["searchOper"]], $_REQUEST["searchField"], $value);
}

$SQL = "SELECT item_id, item, item_cd FROM items ".$where." ORDER BY $sidx $sord";
myTrace($SQL);
$result = mysqli_query($link, $SQL);
if (!$result) {
    myTrace(mysqli_error($link));
    die("Couldn't execute query: ".mysqli_error($link));
}

if ($limit < 0) $limit = 0;

$start = ($limit * $page) - $limit;
if ($start < 0) $start = 0;

$count = mysqli_num_rows($result);
if ($count > 0) {
    $total_pages = ceil($count / $limit);
} else {
    $total_pages = 0;
}

if ($page > $total_pages) {
    $page = $total_pages;
}

$responce->page    = $page;
$responce->total   = $total_pages;
$responce->records = $count;

mysqli_data_seek($result, $start);
for ($i = 0; $row = mysqli_fetch_assoc($result); $i++) {
    if (($limit > 0) && ($i >= $limit)) break;
    $responce->rows[$i]['id']   = $row['item_id'];
    $responce->rows[$i]['cell'] = array($row['item_id'], $row['item'], $row['item_cd']);
} 
echo json_encode($responce);

mysqli_close($link);

?>

在 PHP.INI 文件中启用PHP mysqli 扩展,在“localset.php”脚本(第 15 行)中调整连接参数,最后在浏览器中打开“singlesearch.html”页面。

于 2012-09-16T20:58:17.520 回答