添加查询功能


本实例演示如何从数据库得到数据,并将它们显示在数据网格(datagrid)中。然后演示如何根据用户输入的搜索关键词搜寻显示结果。

创建数据网格(DataGrid)

创建带有分页功能的数据网格(datagrid),然后添加工具栏到其中。

  1. <table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
  2. url="datagrid24_getdata.php" toolbar="#tb"
  3. title="Load Data" iconCls="icon-save"
  4. rownumbers="true" pagination="true">
  5. <thead>
  6. <tr>
  7. <th field="itemid" width="80">Item ID</th>
  8. <th field="productid" width="80">Product ID</th>
  9. <th field="listprice" width="80" align="right">List Price</th>
  10. <th field="unitcost" width="80" align="right">Unit Cost</th>
  11. <th field="attr1" width="150">Attribute</th>
  12. <th field="status" width="60" align="center">Stauts</th>
  13. </tr>
  14. </thead>
  15. </table>

工具栏定义如下:

  1. <div id="tb" style="padding:3px">
  2. <span>Item ID:</span>
  3. <input id="itemid" style="line-height:26px;border:1px solid #ccc">
  4. <span>Product ID:</span>
  5. <input id="productid" style="line-height:26px;border:1px solid #ccc">
  6. <a href="#" class="easyui-linkbutton" plain="true" onclick="doSearch()">Search</a>
  7. </div>

当用户输入查询值并按下查询按钮时,'doSearch' 函数将被调用:

  1. function doSearch(){
  2. $('#tt').datagrid('load',{
  3. itemid: $('#itemid').val(),
  4. productid: $('#productid').val()
  5. });
  6. }

上面的代码调用了 'load' 方法来加载新的数据网格(datagrid)数据。我们需要传递 'itemid' 和 'productid' 参数到服务器。

服务器端代码

  1. include 'conn.php';
  2. $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
  3. $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
  4. $itemid = isset($_POST['itemid']) ? mysql_real_escape_string($_POST['itemid']) : '';
  5. $productid = isset($_POST['productid']) ? mysql_real_escape_string($_POST['productid']) : '';
  6. $offset = ($page-1)*$rows;
  7. $result = array();
  8. $where = "itemid like '$itemid%' and productid like '$productid%'";
  9. $rs = mysql_query("select count(*) from item where " . $where);
  10. $row = mysql_fetch_row($rs);
  11. $result["total"] = $row[0];
  12. $rs = mysql_query("select * from item where " . $where . " limit $offset,$rows");
  13. $items = array();
  14. while($row = mysql_fetch_object($rs)){
  15. array_push($items, $row);
  16. }
  17. $result["rows"] = $items;
  18. echo json_encode($result);

下载 jQuery EasyUI 实例

下载地址