2013-05-10 31 views
2

我有一個jqGrid的下文提到:loadonce:真正導致分頁問題進行的jqGrid

UsersList.aspx

<div id="users" class="grid-right"> 
    <h3>Users</h3> 
    <table id="client-group-users-list"></table> 
    <div id="client-group-users-list-pager"></div> 
</div> 

userlistgroup.js

function createUsersGrid(getUsersForClientGroupUrl) { 
    $('#client-group-users-list').jqGrid({ 
     height: "auto", 
     width: "590", 
     url: getUsersForClientGroupUrl + "?random=" + Math.random(), 
     rowNum: 10, 
     mtype: 'POST', 
     viewrecords: true, 
     postData: { clientGroup: getClientGroupId(), active: true }, 
     datatype: 'json', 
     colNames: ['ClientGroupID', 'Login', 'Role'], 
     //pgbuttons: false, 
     //pgtext: null, 
     //viewrecords: false, 
     gridview: true, 
     colModel: [ 
      { name: 'ClientGroupID', index: 'ClientGroupID', hidden: true }, 
      { name: 'Login', index: 'Login', search: false, width: 130, sorttype: "string" }, 
      { name: 'Role', index: 'Role', search: false, width: 100 } 
     ], 
     caption: "Users for client group: " + getClientGroupName(), 
     pager: '#client-group-users-list-pager', 
     ondblClickRow: function (userId) { 
      editUser(userId); 
     }, 
     sortname: 'Login', 
     sortorder: 'asc', 
     loadui: 'enable', 
     loadError: function (xhr, status) { 
      location.reload(); 
     }   
    }) 
    .jqGrid('navGrid', '#client-group-users-list-pager', 
     { add: false, del: false, edit: false, search: false, view: false }) 
} 

enter image description here

Login列上排序不起作用。但是,如果我把loadonce:true然後它開始工作,但記錄的總數不會反映和分頁功能停止工作。

任何人都可以幫助我處理排序和分頁與datatype: 'json'一起工作。

感謝&問候, 桑托斯·庫馬爾Patro

回答

5

看來你有典型的理解問題的jqGrid如何與服務器交互。

如果使用datatype: 'json'沒有loadonce: true選項然後服務器負責排序,分頁和可選搜索/數據的過濾。在的情況下,對服務器的每個請求都包含重要的輸入參數,其默認值爲:page,rows,sidxsord。還有其他參數_search,nd和其他一些,但在你的情況並不那麼重要。因此,在網格上的內容的第一裝載的jqGrid張貼到URL getUsersForClientGroupUrl財產以後像

page=1&rows=10&sidx=Login&sord=asc 

rowssidxsord參數的值對應的您使用rowNumsortnamesortorder選項的值。服務器應提供請求的數據頁面(數據的第1頁,頁面大小爲10行)。可以使用網格的prmNames選項來重命名page,rows,sidxsord參數。

理解爲:當在「下一頁」 /上一頁」按鈕或如果在列標題的用戶點擊,用戶點擊更改排序,然後jqGrid的向服務器和服務器新的要求是非常重要的應提供數據的基礎上,輸入參數的頁面。

另一方面如果使用loadonce: true選項那麼服務器應該返回所有數據(所有頁面)。加載的數據應該剛剛整理對應與sidxsord選項。加載數據後jqG擺脫datatype"json""local"。接下來的所有排序,分頁和過濾(請參閱filterToolbar方法)或排序(請參閱herehere)將由jqGrid在內部(在客戶端)實施。

如果您需要從服務器重新加載數據,您應該將datatype的值重置爲"json"(請參閱the answer)。通常在beforeRefreshnavGrid的回調中執行此操作。因此,如果用戶點擊導航欄的「刷新」按鈕,網格將從服務器重新加載。

我認爲你只是沒有改變你的服務器代碼,當你使用loadonce: true選項時服務器仍然返回一頁數據。這是不對的。不要忘記在服務器上排序初始數據。

您發佈的代碼中存在一些常見問題。我建議你從URL中刪除"?random=" + Math.random()部分,因爲它沒有任何意義。這種方法通常用於防止在使用情況下緩存服務器響應mtype: "GET"(HTTP GET動詞)。您使用mtype: 'POST'。所以答覆根本不會改變。此外,如果您使用mtype: "GET",則jqGrid會追加已有的URL,其中nd參數的作用與random參數的作用相同。最好的方法是將Cache-Control服務器響應的HTTP標頭設置爲private, max-age=0,並使用prmNames: { nd: null }刪除nd jqGrid選項。有關緩存的更多信息,請參見the answeranother one

另一個問題:你應該明白,你可以撥打createUsersGrid功能只有一次。之後它<table>id="client-group-users-list"將被修改。下一次呼叫createUsersGrid函數將不會做任何事情。我們應該考慮是否需要在函數中放置JavaScript片段,如果它只能被調用一次。或者,可以使用GridUnload方法在下次使用之前銷燬所有現有的jqGrid結構。

如果您希望將被髮送到服務器clientGroup: getClientGroupId()參數是

+0

很酷的解釋與細節。它幫助我很好地理解了loadonce的問題。謝謝:) – 2013-05-21 09:55:11

+0

@santoshkumarpatro:謝謝!不用謝! – Oleg 2013-05-21 10:13:18

0

我也有類似的問題。對我來說,這是服務器代碼。我只是返回第一頁。

rows = model.Select(x => new { x.POID, 
             x.HA1.HA1, 
             x.PONumber, 
              status = x.POStatu.Name, 
             vendor=x.Vendor.Name, 
             x.POCreatedDate, 
             x.POSenttoVendor 
             } 
          ).ToArray().ToPagedList(pageIndex,pageSize). 

所以,我刪除 .ToPagedList(PageIndex的,pageSize的)

0

只是爲了用一個例子完成。

嗨,人們,我傳遞給同樣的問題,我看不到任何這樣的例子。所以,我解決了我的問題,我會讓你舉個例子。

我有一個名爲「estado」(id,nome,sigla,codigo_ibge)的表。我實現了jqGrid Guriddo Responsive以進行所有CRUD操作。從服務器

HTML

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8" /> 

    <!-- We support more than 40 localizations --> 
    <script type="text/ecmascript" src="../../resources/jqGrid/js/i18n/grid.locale-pt-br.js"></script> 

    <!-- This is the Javascript file of jqGrid --> 
    <script type="text/ecmascript" src="../../resources/jqGrid/js/jquery.jqGrid.min.js"></script> 

    <!-- A link to a Boostrap and jqGrid Bootstrap CSS siles--> 
    <link rel="stylesheet" type="text/css" media="screen" href="../../resources/jqGrid/css/ui.jqgrid-bootstrap.css" /> 

    <style type="text/css"> 
     .ui-jqgrid .ui-jqgrid-bdiv { 
       position: relative; 
       margin: 0em; 
       padding:0; 
       /*overflow: auto;*/ 
       overflow-x:hidden; 
       overflow-y:auto; 
       text-align:left; 
      } 
     .customelement .radio-inline input { 
      margin-left: -40px; 
      padding-right: 10px; 
     } 
     .typeahead { 
      z-index: 10051; 
     } 
    </style> 

    <script type="text/javascript"> 
     $.jgrid.defaults.width = 850; 
     $.jgrid.defaults.responsive = true; 
     $.jgrid.defaults.styleUI = 'Bootstrap'; 
     $.jgrid.styleUI.Bootstrap.base.rowTable = "table table-bordered table-striped"; 
     $(document).ready(function() { 

      $("#jqGrid").jqGrid({ 
       url: '../ctrl_gerenciamento/gerenciaEstadoJqGridLoad.php', 
       editurl: '../ctrl_gerenciamento/gerenciaEstadoJqGridEdit.php', 
       datatype: "json", 
       mtype: "GET", 
       page: 1, 
       jsonReader: { 
        page: "obj.currpage", 
        total: "obj.totalpages", 
        records: "obj.totalrecords", 
        repeatitems: false, 
        root: "obj.rows", 
        cell: "cell", 
        id: "0" 
       }, 
       colModel: [ 
        { 
         label: 'ID', 
         name: 'id', 
         width: 20, 
         key: true, 
         editable: false 
        }, 
        { 
         label: 'Nome', 
         name: 'nome', 
         width: 145, 
         editable: true, 
         editrules : { required: true }, 
         search: true, 
         stype: 'text' 
        }, 
        { 
         label: 'Sigla', 
         name: 'sigla', 
         width: 35, 
         editable: true, 
         editrules : { required: true }, 
         search: true, 
         stype: 'text' 
        }, 
        { 
         label: 'Código IBGE', 
         name: 'codigo_ibge', 
         width: 60, 
         editable: true, 
         editrules : { required: true }, 
         search: true, 
         stype: 'text' 
        } 
       ], 
       sortname: 'nome', 
       sortorder : 'asc', 
       loadonce: false, 
       viewrecords: true, 
       width: 785, 
       height: 370, 
       rowNum: 10, 
       pager: "#jqGridPager" 
      }); 

      $('#jqGrid').jqGrid('filterToolbar', {defaultSearch:'cn'}); 

      $('#jqGrid').jqGrid('navGrid',"#jqGridPager", 
       { 
        edit: true, 
        add: true, 
        del: true, 
        search: false, 
        refresh: false, 
        view: false, 
        position: "left" 
       }, 
       { 
        editCaption: "Editar", 
        width: "500", 
        height: "auto", 
        top: "120", 
        left: "500", 
        recreateForm: true, 
        closeAfterEdit: true, 
        errorTextFormat: function (data) { 
         return 'Error: ' + data.responseText 
        } 
       }, 
       { 
        editCaption: "Adicionar", 
        width: "500", 
        height: "auto", 
        top: "120", 
        left: "500", 
        closeAfterAdd: true, 
        recreateForm: true, 
        errorTextFormat: function (data) { 
         return 'Error: ' + data.responseText 
        } 
       }, 
       { 
        editCaption: "Apagar", 
        width: "500", 
        height: "auto", 
        top: "120", 
        left: "500", 
        errorTextFormat: function (data) { 
         return 'Error: ' + data.responseText 
        } 
       }); 
     }); 
    </script> 
</head> 
<body> 
    <br /> 
    <h4> Gerenciamento de Estados </h4> 
    <br /> 
    <div style="margin-left:10px"> 
     <table id="jqGrid"></table> 
     <div id="jqGridPager"></div> 
    </div> 
</body> 
</html> 

負載控制器:

<?php 
    header('Content-Type: application/json; charset=utf-8'); 
    include_once '../../classes/start.php'; 
    $json = new JSON(); 

    $page = $_GET['page']; 
    $limit = $_GET['rows']; 
    $sidx = $_GET['sidx']; 
    $sord = $_GET['sord']; 

    $_search = $_GET['_search']; 
    $filtro = array(); 
    $filtro["nome"]   = isset($_GET["nome"]) ? $_GET["nome"] : null; 
    $filtro["sigla"]  = isset($_GET["sigla"]) ? $_GET["sigla"] : null; 
    $filtro["id"]   = isset($_GET["id"]) ? $_GET["id"] : null; 
    $filtro["codigo_ibge"] = isset($_GET["codigo_ibge"]) ? $_GET["codigo_ibge"] : null; 

    try 
    { 
     if (!$sidx) $sidx = 1; 

     $result = Estado::contarTodosRegistros(); 
     $qtdRegistros = $result[0]['count']; 

     if ($qtdRegistros > 0 && $limit > 0) { 
      $total_pages = ceil($qtdRegistros/$limit); 
     } else { 
      $total_pages = 0; 
     } 

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

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

     $result = null; 
     $saida = null; 

     if ($_search) { 
      $result = Estado::consultarTodosRegistros($sidx, $sord, $start, $limit, $filtro); 
     }else{ 
      $result = Estado::consultarTodosRegistros($sidx, $sord, $start, $limit); 
     } 
     $saida["rows"] = $result; 
     $saida["totalrecords"] = "$qtdRegistros"; 
     $saida["currpage"] = "$page"; 
     $saida["totalpages"] = "$total_pages"; 

     $json->setStatus("ok"); 
     $json->setObjeto($saida); 
    } 
    catch (Exception $ex) 
    { 
     $json->setStatus("erro"); 
     $json->setMensagem($ex->getMessage()); 
    } 

    $json->imprimirJSON(); 

上搜索的工作方法:

public static function consultarTodosRegistros($sidx, $sord, $start, $limit, $filtro='') 
    { 
     $db = Database::conexao(); 
     $temp = 'where 1=1'; 
     if (!empty($filtro)){ 
      if (!empty($filtro["nome"])) { 
       $temp .= " and estado.nome ilike '%". $filtro["nome"]."%'"; 
      } 
      if (!empty($filtro["sigla"])) { 
       $temp .= " and estado.sigla ilike '%". $filtro["sigla"]."%'"; 
      } 
      if (!empty($filtro["id"])) { 
       $temp .= " and estado.id = ". $filtro["id"]; 
      } 
      if (!empty($filtro["codigo_ibge"])) { 
       $temp .= " and estado.codigo_ibge ilike '%". $filtro["codigo_ibge"]."%'"; 
      } 
     } 
     $sql = "select * 
       from updrs.estado 
       $temp 
       order by $sidx $sord 
       limit $limit offset $start"; 

     $result = $db->query($sql); 
     $result = $result->fetchAll(PDO::FETCH_ASSOC); 
     return $result; 
    } 

編輯/添加/ DEL操作

<?php 
include_once '../../classes/start.php'; 

$operacao = $_POST["oper"]; 

$id = !empty($_POST['id']) ? $_POST['id'] : null; 
$codigoIbge = isset($_POST["codigo_ibge"]) ? $_POST["codigo_ibge"] : null; 
$sigla = isset($_POST["sigla"]) ? $_POST["sigla"] : null; 
$nome = isset($_POST["nome"]) ? $_POST["nome"] : null; 

if ($operacao == 'add') 
{ 
    try 
    { 
     $idResult = Estado::insert($codigoIbge, $sigla, $nome); 
     echo "registro atualizado: " . $idResult; 
    } 
    catch (Exception $e) 
    { 
     echo $e->getMessage(); 
    } 
} 

if ($operacao == 'edit') 
{ 
    try 
    { 
     $count = Estado::update($codigoIbge, $sigla, $nome, $id); 
     echo $count . " registro atualizado."; 
    } 
    catch (Exception $e) 
    { 
     echo "Erro: Dados informados são inválidos"; 
    } 

} 

if ($operacao == 'del') 
{ 
    try 
    { 
     $count = Estado::delete($id); 
     echo $count . " registro apagado."; 
    } 
    catch (Exception $e) 
    { 
     echo "Erro: Remoção do registro não permitida"; 
    } 
} 

我希望幫助了一個真實的例子。請享用。