ejemplos php javascript jquery json jqgrid

php - ejemplos - jqGrid con datos JSON representa la tabla como vacía



jqgrid php (9)

¡Yo tengo que trabajar!

El campo de tipo de datos debe ser de tipo de datos . Es sensible a mayúsculas y minúsculas

Intento crear una jqgrid, pero la tabla está vacía. La tabla representa, pero los datos no se muestran.

La información que recibo de la llamada php es:

{ "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 intentado mantener el valor predeterminado. Si el código php ayudará, puedo publicarlo también.


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

Para el json dado, realmente no necesitas la configuración jsonreader. Lo que ha enumerado es el predeterminado de todos modos, además no tiene una sub-red 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"]} ]}


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

Me estoy cansando de perseguir esta escasa documentación y realmente siento que JSON, que es correcto y adecuado para usar en JavaScript, realmente ha recibido una breve cobertura 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.

Alguien 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 es compatible con esto de fábrica)

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

Por favor hagamelo saber. Paso más tiempo en esta parte de mi interfaz que en el resto combinado y todo el tiempo lo dedico a buscar ejemplos de trabajo y "probar cosas", lo cual es cada vez más molesto.

S


El problema también se produce cuando se incluye el script jquery.jqGrid.min.js antes de grid.locale-en.js . Verifique 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 doblemente citado (como lo exigen las especificaciones 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"]} ]}


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 puedas usarlo si te apetece. 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 el siguiente trabajo:

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 de 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 hizo 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();


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

$responce = new stdClass();

¡Antes de que el uso de $ responce pudiera resolverlo todo, y ahora mi cuadrícula funciona bien!

Gracias mis amigos.