简体   繁体   中英

How do I create a table dynamically upon getting a successful ajax response?

I'm returning data from our database and creating a table dynamically. If the call to page1.php is successful, we create a table with one header row and then loop through the results and make some rows. How do I add a single header row? thx!

$.post("page1.php", {user: "homer"}, 
function(data){
// output the header row
  function(test){
  var tblHdr ='<th>'+'Username'+'</th>';
  $(tblHdr).appendTo("#tble");
  };

// output the user data
   $.each(data.userdata, 
     function(i,details){

     var tblRow ='<tr>'+'<td>'details.name+'</td>'+'</tr>';
         $(tblRow).appendTo("#tble");

    });
   }, "json"
);

why do you even need or want that function in there? If you remove the whole function declaration from that block and just append the th as defined then you should be fine. assuming tblHdr and tblRow are defined somewhere.

$.post("page1.php", {user: "homer"}, 
function(data){
// output the header row

  var tblHdr ='<th>'+'Username'+'</th>';
  $(tblHdr).appendTo("#tble");


// output the user data
   $.each(data.userdata, 
     function(i,details){

     var tblRow ='<tr>'+'<td>'details.name+'</td>'+'</tr>';
         $(tblRow).appendTo("#tble");

    });
   }, "json"
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM