Pregunta

Estoy intentando crear un jqgrid, pero la tabla está vacía. La tabla se representa, pero los datos no se muestran.

Los datos que recibo de la llamada php son:

{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]},
{"id":"2:4","cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]},
{"id":"2:5","cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]},
{"id":"2:6","cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]},
{"id":"2:7","cell":["7","image","Photography","To recognize photography knowledge and skills","0"]},
{"id":"2:8","cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]},
{"id":"2:10","cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]},
{"id":"2:11","cell":["11","image","World Conservation","World Conservation Badge","0"]}
]}

La configuración de JavaScript se ve así:

$("#"+tableId).jqGrid ({
    url:'getAwards.php?id='+classId,
    dataType : 'json',
    mtype:'POST',
    colNames:['Id','Badge','Name','Description',''],
    colModel : [
        {name:'awardId', width:30, sortable:true, align:'center'},
        {name:'badge', width:40, sortable:false, align:'center'},
        {name:'name', width:180, sortable:true, align:'left'},
        {name:'description', width:380, sortable:true, align:'left'},
        {name:'selected', width:0, sortable:false, align:'center'}
        ],
    sortname: "awardId",
    sortorder: "asc",
    pager: $('#'+tableId+'_pager'),
    rowNum:15,
    rowList:[15,30,50],
    caption: 'Awards',
    viewrecords:true,
    imgpath: 'scripts/jqGrid/themes/green/images',
    jsonReader : { 
        root: "rows", 
        page: "page", 
        total: "total", 
        records: "records", 
        repeatitems: true, 
        cell: "cell", 
        id: "id",
        userdata: "userdata", 
        subgrid: {root:"rows", repeatitems: true, cell:"cell" } 
    },
    width: 700,
    height: 200
});

El HTML se ve así:

<table class="awardsList" id="awardsList2" class="scroll" name="awardsList" />
<div id="awardsList2_pager" class="scroll"></div>

No estoy seguro de que necesite definir jsonReader, ya que he tratado de mantener el valor predeterminado. Si el código php ayuda, también puedo publicarlo.

¿Fue útil?

Solución

¡Lo puse a trabajar!

El campo dataType debe ser datatype . Es sensible a mayúsculas y minúsculas.

Otros consejos

El problema también se produce cuando incluye el script jquery.jqGrid.min.js antes de grid.locale-en.js . Compruebe esto si hay algún problema con la llamada al método del controlador.

Experimenté el mismo problema al migrar de jqGrid 3.6 a jqGrid 3.7.2. El problema era que mi JSON no estaba correctamente entre comillas dobles (como lo requiere la especificación JSON). jqGrid 3.6 toleró mi JSON no válido pero jqGrid 3.7 es más estricto.

Consulte aquí: http://simonwillison.net/2006/Oct/11/json /

Inválido :

{
page:"1",
total:1,
records:"10",
rows:[
    {"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
    {"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
    {"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]}
]}

Válido :

{
"page":"1",
"total":1,
"records":"10",
"rows":[
    {"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
    {"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
    {"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]}
]}

También lo hice funcionar: el tipo de datos es la ortografía correcta: se muestra de esa manera en el ejemplo, pero es inconsistente con todo más en la biblioteca, por lo que fue fácil equivocarse

Me estoy cansando de perseguir esta escasa documentación y realmente siento que JSON, que es correcto y apropiado para usar en JavaScript, realmente ha recibido una cobertura breve a favor de XML. Python y JavaScript juntos, a través de JSON, es una combinación realmente fuerte, pero es una lucha constante con esta biblioteca en particular.

Cualquiera con una alternativa que:

1 > Admite correctamente los temas de jQuery UI (incluidas las esquinas redondeadas) ( http://datatables.net tiene un soporte mucho mejor para los temas)

2 > Permite cambiar el tamaño de las columnas ( http://datatables.net no admite esto de forma inmediata)

3 > Permite sub-cuadrículas ( http://datatables.net le permite hacer lo que quiera aquí, a través de un evento)

por favor hágamelo saber. Paso más tiempo en esta parte de mi interfaz que en el resto de la combinación y es todo el tiempo dedicado a buscar ejemplos de trabajo y "probar cosas". lo cual se está volviendo molesto.

S

Esta podría ser una publicación anterior, pero publicaré mi éxito solo para ayudar a otros.

Su JSON debe estar en este formato:

{
"rows": [
    {
        "id": 1,
        "cell": [
            1,
           "lname",
            "fname",
            "mi",
            phone,
            "cell1",
            "cell2",
            "address",
            "email"
        ]
    },
    {
        "id": 2,
        "cell": [
            2,
            "lname",
            "fname",
            "mi",
            phone,
            "cell1",
            "cell2",
            "address",
            "email"
        ]
    }
]

}

y escribí este modelo en Zend para que pueda usarlo si lo desea. Manipúlalo como quieras.

public function fetchall ($sid, $sord)
{
    $select = $this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
    $select->setIntegrityCheck(false)
           ->join('Subdiv', 'Subdiv.SID = Contacts.SID', array("RepLastName" => "LastName", 
                                                                "Subdivision" => "Subdivision",
                                                                "RepFirstName" => "FirstName"))
           ->order($sid . " ". $sord);

    $resultset = $this->getDbTable()->fetchAll($select);
    $i=0;
    foreach ($resultset as $row) {
        $entry  = new Application_Model_Contacts();

        $entry->setId($row->id);
        $entry->setLastName($row->LastName);
        $entry->setFirstName1($row->FirstName1);
        $entry->setFirstName2($row->FirstName2);
        $entry->setHomePhone($row->HomePhone);
        $entry->setCell1($row->Cell1);
        $entry->setCell2($row->Cell2);
        $entry->setAddress($row->Address);
        $entry->setSubdivision($row->Subdivision);
        $entry->setRepName($row->RepFirstName . " " . $row->RepLastName);
        $entry->setEmail1($row->Email1); 
        $entry->setEmail2($row->Email2);

        $response['rows'][$i]['id'] = $entry->getId(); //id
        $response['rows'][$i]['cell'] = array (
                                                $entry->getId(),
                                                $entry->getLastName(),
                                                $entry->getFirstName1(),
                                                $entry->getFirstName2(),
                                                $entry->getHomePhone(),
                                                $entry->getCell1(),
                                                $entry->getCell2(),
                                                $entry->getAddress(),
                                                $entry->getSubdivision(),
                                                $entry->getRepName(),
                                                $entry->getEmail1(),
                                                $entry->getEmail2()
                                            );
        $i++;

    }
    return $response;
}

Los chicos solo quieren ayudarte en esto. Obtuve lo siguiente:

JSON

var mydata1 = { "page": "1", "total": 1, "records": "4","rows": [{ "id": 1, "cell": ["1", "cell11", "values1" ] },
    { "id": 2, "cell": ["2", "cell21", "values1"] },
    { "id": 3, "cell": ["3", "cell21", "values1"] },
    { "id": 4, "cell": ["4", "cell21", "values1"] }
]};

// Marque debajo de la línea importante. tipo de datos "jsonstring" funcionó para mí en lugar de "json".

datatype: "jsonstring",

contentType: "application/json; charset=utf-8",

datastr: mydata1,

colNames: ['Id1', 'Name1', 'Values1'],

colModel: [
      { name: 'id1', index: 'id1', width: 55 },
      { name: 'name1', index: 'name1', width: 80, align: 'right', sorttype: 'string' },
      { name: 'values1', index: 'values1', width: 80, align: 'right', sorttype: 'string'}],

Saludos,

En mi caso, el problema fue causado por la siguiente línea de código PHP (que fue tomada de la demostración jqGrid):

$responce->page = $page;

Lo que está mal aquí es que: estoy accediendo a la página de propiedades del objeto $ responce sin crearlo primero. Esto provocó que Apache mostrara el siguiente mensaje de error:

Strict Standards: Creating default object from empty value in /home/mariusz/public_html/rezerwacja/apps/frontend/modules/service/actions/actions.class.php on line 35

Y finalmente el mensaje de error solía enviarse al lector json dentro del script.

Solucioné el problema creando un objeto vacío:

$responce = new stdClass();

No creo que su ID sea del tipo correcto, creo que debería ser un int.

Para el json dado, realmente no necesita la configuración de jsonreader. Lo que ha enumerado son los valores predeterminados de todos modos, además de que no tiene una subcuadrícula en su json.

Prueba esto:

{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":1 ,"cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":2,"cell":["2","image","Link Badge","When you are invested as a Scout, you maybe eligible to receive a Link Badge. (See page 45)","0"]},
{"id":3,"cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]},
{"id":4,"cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]},
{"id":5,"cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]},
{"id":6,"cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]},
{"id":7,"cell":["7","image","Photography","To recognize photography knowledge and skills","0"]},
{"id":8,"cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]},
{"id":9,"cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]},
{"id":10,"cell":["11","image","World Conservation","World Conservation Badge","0"]}
]}

Estaba trabajando con WAMP 2.4, estaba loco con este problema, probé muchas cosas, como instalar versiones anteriores de PHP y 5.2, incluso lo intenté en Windows XP y muchas opciones de jqGrid. Bueno, gracias a Oleg finalmente y a Mariusz, encuentro la única línea:

$responce = new stdClass(); 

Antes el uso de $ responce podía resolverlo todo, y ahora mi grilla funciona ¡Genial!

Gracias mis amigos.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top