The js implementation displays the json array in the foreground table

  • 2021-07-10 18:11:51
  • OfStack

In the recent study, I encountered a small problem, how to display JSON array in the foreground table, and finally solved this problem after a reference and study. The specific code is as follows:

(Premise: The JSON string obtained by ajax must be standard in order to parse correctly. The code for obtaining data in the database in the background is omitted.)

1. Foreground JS code (using the js library file that was previously introduced into JQuery)


$.ajax({
 type: "GET",
 url: "UserList.ashx?Action=List",// Utilization ajax Request background and return value 
 // data: "json",
 success: function (result) {//result The value returned for the background , Yes json The form of a string 
 // alert(result);
 var obj = JSON.parse(result);// Analyse json The string is json Object form 
 var trStr = '';// Dynamic splicing table
 // var html = '';
 for (var i = 0; i < obj.length; i++) {// Loop through json Object for each of the 1 Data are displayed in the corresponding td Medium 
 trStr += '<tr class="example">';// Tabular form of splice specification 
 trStr += '<td width="15%" style="display:none" id="user">' + obj[i].NVFID + '</td>';// Primary key value of data table 
 trStr += '<td width="15%">' + obj[i].USERCODE + '</td>';// Field values corresponding to array tables 
 trStr += '<td width="15%">' + obj[i].USERNAME + '</td>';
 trStr += '<td width="15%">' + obj[i].USERPWD + '</td>';
 trStr += '<td>' + obj[i].PHONEIMEI + '</td>';
 trStr += '<td>' + obj[i].BMMC + '</td>';
 /* Classically, the value corresponding to the primary key should be used as json In order to use it in the background, it can be passed in the form of */
 trStr += "<td><a href='#'style='text-decoration:none' onclick='Delete(\"" + obj[i].NVFID + "\")'> Delete </a><td>";
 trStr += '</tr>';  
 } 
 $("#tbody").html(trStr);// Utilize html Method will splice the table Add to tbody Medium return;
 },
 error: function (error) {
 alert(error);
 }
 });

2. Foreground HTML code


<div>
 <!--  A table that displays background data  -->
 <table id="mainTable" class="display hover" border="1">
 <thead>
 <tr>
 <th> User number </th>
 <th> User name </th>
 <th> User password </th>
 <th> Mobile phone number </th>
 <th> Department name </th>
 <th width="10%"> Operation </th>
 </tr>
 </thead>
 <tbody id="tbody">
 <tr id="content" class="example">
 <td id="UserCode">2</td>
 <td id="UserName">2</td>
 <td id="UserPwd">2</td>
 <td id="Bmmc">2</td>
 <td id="Phone">2</td>
 </tr>
 </tbody>
 </table>
 </div>

Related articles: