Загрузка данных в HTML таблицы с использованием AJAX JavaScript не работает - PullRequest
0 голосов
/ 05 августа 2020

У меня есть данные, хранящиеся в файле json, например:

[
["cell1", "cell2", "cell3"],
["cell4", "cell5", "cell6"]
...
]

Я хочу преобразовать данные json в таблицу html, поэтому я создал код ниже (html структура + загрузка данных отдельно из специального json файла данных, расположенного в том же каталоге "строк. json" ):

<body>
    <table id="tab">
        <thead>
            <tr>
                <th>column_1</th>
                <th>column_2</th>
                <th>column_3</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

<script type="text/javascript">
        const TabBody = document.querySelector("#tab > tbody") 
        function loadData() {
            const request = new XMLHttpRequest();
            request.open("get", "rows.json");
            request.onload = () => {
                try {
                    const json = JSON.parse(request.responseText);
                    populateTable(json);
                    }  catch (e) {
                        console.warn("error");
                    }   
                };
                
            request.send();
        }
        function populateTable(json){
            
            while(TabBody.firstChild){TabBody.removeChild(TabBody.firstChild);}

            json.forEach((row) => { 
                const tr = document.createElement("tr");

                row.forEach((cell) => {
                    const td = document.createElement("td");
                    td.textContent = cell;
                    tr.appendChild(td);})
                
                TabBody.appendChild(tr);
            })            
        }
    </script>
</body>

Код не работает, и тело таблицы не загружено. Возможно, код неправильный или неэффективный, и есть способы сделать это лучше ..

Ответы [ 2 ]

1 голос
/ 05 августа 2020

Ваша функция populateTable кажется правильной, я скопировал ее во фрагмент, и она работает нормально.

  • Получаете ли вы правильные данные из XMLHttpRequest?
  • Где вы вызываете функцию loadData? Вы забыли позвонить?

const data = [
  ["cell1", "cell2", "cell3"],
  ["cell4", "cell5", "cell6"]
]

const TabBody = document.querySelector("#tab > tbody");

function populateTable(json) {

  while (TabBody.firstChild) {
    TabBody.removeChild(TabBody.firstChild);
  }

  json.forEach((row) => {
    const tr = document.createElement("tr");

    row.forEach((cell) => {
      const td = document.createElement("td");
      td.textContent = cell;
      tr.appendChild(td);
    })

    TabBody.appendChild(tr);
  })
}

populateTable(data);
<table id="tab">
  <thead>
    <tr>
      <th>column_1</th>
      <th>column_2</th>
      <th>column_3</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
0 голосов
/ 05 августа 2020

В этом случае вы можете использовать Табулятор. вы можете загрузить данные json внутрь, и это дает вам множество функций и возможность стилизовать таблицу.

здесь вы можете прочитать о том, как вставить данные из ajax запроса: http://tabulator.info/docs/4.1/data#ajax

, если вы хотите сделать запрос и ввести ответ в таблицу, вы можете сделать это после того, как получите ответ от вашего кода:

var table = new Tabulator("#example-table", {
                height: '70%', // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
                data: res.json, //assign data to table, json response
                layout: "fitDataFill", //fit columns to width of data
                pagination: "local",
                paginationSize: 10,
                paginationSizeSelector: [5, 10, 15, 20],
                movableColumns: true,
                selectable: true,
                columns: [
                    {
                        formatter: "buttonCross", align: "center", title: "del", headerSort: false, cellClick: function (e, cell) {
                            if (confirm('Are you sure you want to delete this entry?'))
                                cell.getRow().delete();
                            console.log(rowJson = cell.getRow().getData())
                        }
                    },
                    { title: "id", field: "id", sorter: "number" },
                    { title: "Name", field: "name", sorter: 'string' },
                    { title: "phone", field: "phone", sorter: "number" },
                    { title: "email", field: "email", sorter: 'string' },
                    { title: "location", field: "location", sorter: 'string' },
                    { title: "price/night", field: "price", sorter: 'number' },
                    { title: "number of rooms", field: "roomsnumber", sorter: 'number' },
                    { title: "capacity", field: "capacity", sorter: 'number' },
                    { title: "available", field: "available", sorter: 'string' },
                    { title: "start time", field: "startTime", sorter: 'string' },
                    { title: "date", field: "date", sorter: "date", },
                ]
                
            });

это очень просто в использовании и есть много функций ..

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...