en mi web.php tengo un modelo que recurro a json:
Route::get('operatore/ajax',function(PdfDettagli $PdfDettagli){ return $PdfDettagli::all()->toJson(); });
En mi opinión, tengo una tabla:
<table id="table" class="display" style="width:100%"> <thead> <tr> <th>nome</th> <th>posizione</th> </tr> </thead> </table>
y el siguiente jquery:
script type="text/javascript"> $(document).ready(function(){ $('#table').DataTable({ "ajax": "/operatore/ajax", "columns": [ {"data":"nome" }, {"data":"posizione"} ] }); }); </script>
Debería leer el modelo como json y cargarlo para llenar la tabla automáticamente, pero no lo hará.
La tabla es esta: https://datatables.net/ y en el manual he leído la sección sobre ajax: https://datatables.net/manual/ajax y creo que he hecho como en los ejemplos pero no funciona
Si entro operatore/ajax, la respuesta devuelta tiene el siguiente formato:
[{"id":1,"posizione":"operatori\/Giuseppe-Pentangelo\/pdf\/carta-di-identita\/K3hXUVBjUZqBMLgWG2SbMCMdLVK5mcTJTcusSImB.png","nome":"img_avatar.png","id_veicolo":null,"id_operatore":1,"id_categoria_pdf":1,"created_at":"2022-02-15T12:02:53.000000Z","updated_at":"2022-02-15T12:02:53.000000Z"},
Probé model->asArray también y la respuesta que da es diferente pero tampoco funciona
Editar: la consola del navegador da este error:
Uncaught TypeError: f is undefined jQuery 17 <anonymous> http://localhost:8000/pdf:12 jQuery 13 jquery.dataTables.min.js:49:73 jQuery 17 ha i success c fireWith l o (Asinc.: EventHandlerNonNull) send ajax sa ha e n each each n DataTable <anonima> http://localhost:8000/pdf:12 jQuery 13 e t (Asinc.: setTimeout handler) l c fireWith fire c fireWith ready B (Asinc.: EventListener.handleEvent) <anonima> <anonima> <anonima>
DataTable por defecto espera una respuesta en este formato:
{ "data" : [...] }
Su punto final, en cambio, devuelve directamente la matriz de datos.
Para solucionar su problema, simplemente modifique su configuración de DataTable desde:
"ajax": "/operatore/ajax"
a:
"ajax": { "url": "/operatore/ajax", "dataSrc": "" }
Fuente: https://datatables.net/examples/ajax/custom_data_property.html