Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 15
  1. #1

    Creare Tabella da json esterno

    Buonasera,
    ho un problema. Non riesco a fargli leggere il file json esterno
    codice:
    let jsonData = JSON.stringify(newURL('http://127.0.0.1:5500/html/ltr/listaVlt.json'));        console.log(jsonData); 
    
    console.log(typeofJSON.stringify(jsonData));
    In console di Chrome ho questi errori

    "http://127.0.0.1:5500/html/ltr/listaVlt.json"

    string

    Giustamente non posso ciclarci sopra e fare tabella in quanto non visualizza dati in questo modo
    [{"varName":"nome","varRegione":"regione","varCitta ":"citta","varNum":"20","varDataAgg":"05/04/2023"},.
    ma mi da "http://127.0.0.1:5500/html/ltr/listaVlt.json"
    jquery.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in "http://127.0.0.1:5500/html/ltr/listaVlt.json"
    at p (jquery.min.js:2:1104)
    at Function.each (jquery.min.js:2:2964)
    at convert (tables_prova_Jason_jQuery.html:88:12)
    at HTMLButtonElement.onclick (tables_prova_Jason_jQuery.html:12:42)

  2. #2
    Moderatore di Programmazione L'avatar di alka
    Registrato dal
    Oct 2001
    residenza
    Reggio Emilia
    Messaggi
    24,472
    Quote Originariamente inviata da xxiaprile753 Visualizza il messaggio
    In console di Chrome ho questi errori [...]
    A prima vista, sembra che tu stia cercando di convertire dal formato JSON la stringa che contiene l'indirizzo, piuttosto che il contenuto del file stesso.

    Devi fare una GET HTTP usando jQuery.ajax(), fetch() o equivalente.

    Ciao!
    MARCO BREVEGLIERI
    Software and Web Developer, Teacher and Consultant

    Home | Blog | Delphi Podcast | Twitch | Altro...

  3. #3
    Utente di HTML.it L'avatar di ninja72
    Registrato dal
    May 2020
    residenza
    -
    Messaggi
    319
    Alka ha perfettamente ragione, direi di utilizzare fetch API, e visto che questa ritorna una promise potresti utilizzare async/await per gestire il dato ritornato.

    codice:
    const jsonData = async () => {
        return (await fetch('http://127.0.0.1:5500/html/ltr/listaVlt.json')).json()
    }
    
    void async function() {
        const result = await jsonData()
        console.log(result)
    }()

  4. #4
    abbandonata ipotesi del file esterno ho fatto in questo modo
    codice:
    /* Formatting function for row details - modify as you need */function format(d) {
        // `d` is the original data object for the row
        return (
            '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
            '<tr>' +
            '<td>Full name:</td>' +
            '<td>' +
            d.name +
            '</td>' +
            '</tr>' +
            '<tr>' +
            '<td>Extension number:</td>' +
            '<td>' +
            d.extn +
            '</td>' +
            '</tr>' +
            '<tr>' +
            '<td>Extra info:</td>' +
            '<td>And any further details here (images etc)...</td>' +
            '</tr>' +
            '</table>'
        );
    }
     
    function test() {
    
        var data = [
            {
              "id": "1",
              "name": "Tiger Nixon",
              "position": "System Architect",
              "salary": "$320,800",
              "start_date": "2011/04/25",
              "office": "Edinburgh",
              "extn": "5421"
            },
            {
              "id": "2",
              "name": "Garrett Winters",
              "position": "Accountant",
              "salary": "$170,750",
              "start_date": "2011/07/25",
              "office": "Tokyo",
              "extn": "8422"
            },
            {
              "id": "3",
              "name": "Ashton Cox",
              "position": "Junior Technical Author",
              "salary": "$86,000",
              "start_date": "2009/01/12",
              "office": "San Francisco",
              "extn": "1562"
            },
            {
              "id": "4",
              "name": "Cedric Kelly",
              "position": "Senior Javascript Developer",
              "salary": "$433,060",
              "start_date": "2012/03/29",
              "office": "Edinburgh",
              "extn": "6224"
            },
            {
              "id": "5",
              "name": "Airi Satou",
              "position": "Accountant",
              "salary": "$162,700",
              "start_date": "2008/11/28",
              "office": "Tokyo",
              "extn": "5407"
            },
          ];
    
          let table = $("#example");
          $.each(data, function(i, item){
            let tr = $("<tr>");
                  
            // Get the values of the current object in the JSON data
            let vals = Object.values(item);
                  
            // Loop through the values and create table cells
                $.each(vals, (i, elem) => {
                    let td = $("<td>");
                    td.text(elem); // Set the value as the text of the table cell
                    tr.append(td); // Append the table cell to the table row
                });
                  table.append(tr); // Append the table row to the table
            });
            //container.append(table) // Append the table to the container element
        
            //Dopo aver costruito la tabella la rendo tabella
        table.DataTable({
            retrieve: true,
            columns: [
                {
                    className: 'dt-control',
                    orderable: true,
                    data: null,
                    defaultContent: '',
                },
                { data: 'name' },
                { data: 'position' },
                { data: 'office' },
                { data: 'salary' },
            ],
            order: [[1, 'asc']],
        });
     
        // Add event listener for opening and closing details
        $('#example tbody').on('click', 'td.dt-control', function () {
            var tr = $(this).closest('tr');
            var row = table.row(tr);
     
            if (row.child.isShown()) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');
            } else {
                // Open this row
                row.child(format(row.data())).show();
                tr.addClass('shown');
            }
        });
    
    };

  5. #5
    il codice html
    codice:
    <tableid="example"class="display"style="width:100%">                                        <thead>
                                                <tr>
                                                    <th></th>
                                                    <th>Name</th>
                                                    <th>Position</th>
                                                    <th>Office</th>
                                                    <th>Salary</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <button id="btn" onclick="test()"> test </button>
                                            </tbody>
    
    </table>

  6. #6
    i risultato è che mi da :
    datatable warning incorrect column count e il mi crea tabella con i dati per tutte le colonne anche per quelle che non sono presenti su htlm, ma vorrei un risultato come l'esempio https://datatables.net/examples/api/row_details.html

  7. #7
    Utente di HTML.it L'avatar di ninja72
    Registrato dal
    May 2020
    residenza
    -
    Messaggi
    319
    Va corretta questa parte:

    codice:
    <tbody>
       <button id="btn" onclick="test()"> test </button>
    </tbody>
    In pratica devi spostare l'elemento "button" fuori dalla table (solo per migliore leggibilità), poi devi eliminare il tag "tbody".

  8. #8
    ho fatto come detto ma non cambia nulla. La tabella viene visualizzata per intero di tutte le colonne...
    Io vorrei che si visualizzassero n-colonne e che ci sia il pulsante per espandere dove si vedono altri dati. Come da esempio del link, che peraltro ho riportato da me e non funziona mentre sul sito si.

  9. #9
    Utente di HTML.it L'avatar di ninja72
    Registrato dal
    May 2020
    residenza
    -
    Messaggi
    319
    Perdonami ma ti spieghi veramente male, detto questo ti riscrivo il codice corretto, anche se la soluzione era abbastanza intuibile visto che è copiato (quasi) pari pari dalla documentazione ufficiale.

    ps. Sconsiglio vivamente il tuo tipo di approccio, che va ad inserire i dati json o di altro tipo all'interno del file javascript.

    html file

    codice:
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
        <title>Document</title>
    </head>
    
    <body>
        <table id="example" class="display" style="width:100%">
            <thead>
                <tr>
                    <th></th>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Salary</th>
                </tr>
            </thead>
            <button id="btn" onclick="test()"> test </button>
        </table>
    
        <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
        <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
        <script>
            /* Formatting function for row details - modify as you need */
            function format(d) {
                // `d` is the original data object for the row
                return (
                    '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
                    '<tr>' +
                    '<td>Full name:</td>' +
                    '<td>' +
                    d.name +
                    '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td>Extension number:</td>' +
                    '<td>' +
                    d.extn +
                    '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td>Extra info:</td>' +
                    '<td>And any further details here (images etc)...</td>' +
                    '</tr>' +
                    '</table>'
                );
            }
    
           function test() {
                var table = $('#example').DataTable({
                    ajax: './data.json',
                    columns: [
                        {
                            className: 'dt-control',
                            orderable: false,
                            data: null,
                            defaultContent: '',
                        },
                        { data: 'name' },
                        { data: 'position' },
                        { data: 'office' },
                        { data: 'salary' },
                    ],
                    order: [[1, 'asc']],
                });
    
                // Add event listener for opening and closing details
                $('#example tbody').on('click', 'td.dt-control', function () {
                    var tr = $(this).closest('tr');
                    var row = table.row(tr);
    
                    if (row.child.isShown()) {
                        // This row is already open - close it
                        row.child.hide();
                        tr.removeClass('shown');
                    } else {
                        // Open this row
                        row.child(format(row.data())).show();
                        tr.addClass('shown');
                    }
                });
            };
        </script>
    </body>
    
    </html>
    data.json
    codice:
    {
        "data": [
            {
                "id": "1",
                "name": "Tiger Nixon",
                "position": "System Architect",
                "salary": "$320,800",
                "start_date": "2011/04/25",
                "office": "Edinburgh",
                "extn": "5421"
            },
            {
                "id": "2",
                "name": "Garrett Winters",
                "position": "Accountant",
                "salary": "$170,750",
                "start_date": "2011/07/25",
                "office": "Tokyo",
                "extn": "8422"
            },
            {
                "id": "3",
                "name": "Ashton Cox",
                "position": "Junior Technical Author",
                "salary": "$86,000",
                "start_date": "2009/01/12",
                "office": "San Francisco",
                "extn": "1562"
            },
            {
                "id": "4",
                "name": "Cedric Kelly",
                "position": "Senior Javascript Developer",
                "salary": "$433,060",
                "start_date": "2012/03/29",
                "office": "Edinburgh",
                "extn": "6224"
            },
            {
                "id": "5",
                "name": "Airi Satou",
                "position": "Accountant",
                "salary": "$162,700",
                "start_date": "2008/11/28",
                "office": "Tokyo",
                "extn": "5407"
            }
        ]
    }

  10. #10
    Ti ringrazio della risposta, infatti come dici tu ho abbandonato quello strada. I dati del Json li ho messi dentro il file js.
    Sono riuscito a farlo funzionare piu o meno come vorrei...mi mancano solo delle cose che non capisco come farle visualizzare
    - il + e - che è presente alla sinistra di ogni riga di dati
    - non mi va piu la nav bar che si espande cliccando sul breadcrumb
    - se clicco due volte su test mi da questo errore : Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3 (ho provato a gestirlo con un "ricercaFatta 0/1")
    - Non risco a far funzionare il cancella (ora ho gli faccio fare refresh ma vorrei che venga eliminata la tabella visualizzata)

Tag per questa discussione

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.