سؤال

I need collect data from the HTML table and send it to the server. I must use JQuery. there is my table

    <table id="table" border=1>
    <thead> <tr>
    <th>First</th>
    <th>Last</th>
    <th>Date of birth</th>
    <th>City</th>
    </tr></thead>
    <tbody>
    <tr>
    <td>TEXT1</td>
    <td>TEXT2</td>
    <td>TEXT3</td>
    <td>TEXT4</td>
    </tr>
    <tr>
    <td>TEXT5</td>
    <td>TEXT6</td>
    <td>TEXT7</td>
    <td>TEXT8</td>
     </tr>
    <tr>
    <td>TEXT9</td>
    <td>TEXT10</td>
    <td>TEXT11</td>
    <td>TEXT12</td>
   </tr>
   </tbody>
   </table>
هل كانت مفيدة؟

المحلول

You could achieve it in this manner,

First we select all the data from the table cell's and then we send it to the server side via jquery ajax

JQuery Code:

<script  type="text/javascript" src="jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function(){
    var dataArr = [];
    $("td").each(function(){
        dataArr.push($(this).html());
    });
    $('#sendServer').click(function(){
        $.ajax({
              type : "POST",
              url : 'server.php',
              data : "content="+dataArr,
              success: function(data) {
                  alert(data);// alert the data from the server
              },
              error : function() {
              }
        });
    });
});
</script>

Html code:

<table id="table" border=1>
    <thead> <tr>
    <th>First</th>
    <th>Last</th>
    <th>Date of birth</th>
    <th>City</th>
    </tr></thead>
    <tbody>
    <tr>
    <td>TEXT1</td>
    <td>TEXT2</td>
    <td>TEXT3</td>
    <td>TEXT4</td>
    </tr>
    <tr>
    <td>TEXT5</td>
    <td>TEXT6</td>
    <td>TEXT7</td>
    <td>TEXT8</td>
     </tr>
    <tr>
    <td>TEXT9</td>
    <td>TEXT10</td>
    <td>TEXT11</td>
    <td>TEXT12</td>
   </tr>
   </tbody>
   </table>

<input id="sendServer" name="sendServer" type="button" value="Send to Server" />

in your server side PHP Code (here i am sending back what has been posted to server, just for the example)

<?php 
echo $_REQUEST['content'];
?>

نصائح أخرى

possible duplicate of convert a HTML table data into a JSON object in jQuery

but solution is

var tbl = $('table#whatever tr').map(function() {
  return $(this).find('td').map(function() {
    return $(this).html();
  }).get();
}).get();

Then just use $.json (or whatever library you want) to turn that into a JSON string.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top