Создать таблицу из json (JSON .stringify (res [0])) - вывод в строку - должен быть преобразован в таблицу в html - PullRequest
0 голосов
/ 07 апреля 2020

Мне нужно создать таблицу из JSON, я получаю вывод в виде строки, и она должна быть напечатана в формате таблицы в HTML

function apicall(){

        var id = document.getElementById('idval').value;


        var url1 = '**********************';
        var token = sessionStorage.getItem('MyUniqueUserToken');
        var data1 = {"ip":id};
        var success = {};
        var dataType = {};

        $.ajax({
        url: url1,
        data: data1,
        type: "GET",
        beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'token '+token);},
        success: function(res) { 

            document.getElementById('output').innerHTML =JSON.stringify(res[0]);
                               }

  });



}

введите описание изображения здесь

1 Ответ

0 голосов
/ 07 апреля 2020

Предполагается, что res является ответом как JSON, поэтому вместо

 document.getElementById('output').innerHTML =JSON.stringify(res[0]);

вы должны поместить свой ответ в al oop (учитывая, что у вас есть пустая таблица с ячейками = полями output0 to output4

        var i=0;
        response.data.forEach(function(field) {

           //here you create the table cells if there are 5 fields 
             that would be 5 cells as I do not know the structure just 
             pseudo code
             document.getElementById('output'+i).innerHTML = JSON.stringify(res[i]);
             i = i+1;
          }

Если вы хотите полудинамически создавать строки таблицы, у вас должна быть таблица с исправлением строки верхнего и нижнего колонтитула, а тело таблицы в качестве якоря, к которому вы добавляете созданные строки, может выглядеть следующим образом (частично) псевдокод) -PLAIN vanilla javascript, как мне не нравится jquery:

  // We need a table definition for creating headers and interpreting JSON date
  var tdataRow = [{
        "output0" : field.output0,
        "output1" : field.output1,
        "output2" : field.output2,
        "output3" : field.output3;
       "output4" : field.output4
                    }];
  // Then in jour ajax
  response.data.forEach(function(field) {         
     var columnHeadings = Object.keys(tdataRow[0]);
     var tableRef = document.getElementById("tbody" + "my_test_table");
     var columnCount = 5; // Could be derived from number of headings
     var tableLength = tableRef.getElementsByTagName("tr").length;// we get the number of the existing table rows
 var trowID = tableLength + 1; // we append at the end of existing rows
 var tableRow = tableRef.insertRow(tindex);
 for (var j = 0; j < columnCount; j++) { /* Each column */
    var cell = tableRow.insertCell(-1);
    cell.setAttribute("id", columnHeadings[j] ); 
    var obj = tdataRow[0];
    cell.innerText = obj[columnHeadings[j]]; // we get the field names from the header
 }
 tableRow.setAttribute("id", "row" + "my_test_table" + j );
 // examples how to style and use classes 
 tableRow.classList.add("table");
 tableRow.classList.add("clickable-row");
 tableRow.setAttribute("align","center");
 // if you want to catch clicks on the row
 tableRow.addEventListener("click", function(){
 // do something with the row e.g. highlight/ get values etc
  }
 }

Второе решение может быть преобразовано в полностью автоматизированное / динамическое c решение, в котором все создается из JSON - но сначала маленькие шаги.

...