【问题标题】:Collect data from html table use jquery使用jquery从html表中收集数据
【发布时间】:2012-11-16 00:38:00
【问题描述】:

我需要从 HTML 表中收集数据并将其发送到服务器。我必须使用 JQuery。 有我的桌子

    <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>

【问题讨论】:

  • 你想收集什么数据?
  • 你必须先回答以前的问题才能在这里提问
  • 你了解过如何使用jquery的基础知识吗?访问元素及其值?阅读文档可能会为您提供更好的服务。
  • 我需要从 td 标签(每个单元格)收集所有数据。
  • 亲爱的 ryadavilli 感谢 cmets。我会跟随他们,但我现在没有时间寻找文档。无论如何,我稍后都会这样做,并阅读有关如何使用 jquery 的基础知识的更多信息。但是现在请帮我完成这项任务。

标签: jquery html html-table collect


【解决方案1】:

你可以通过这种方式实现它,

首先我们从表格单元格中选择所有数据,然后通过 jquery ajax 将其发送到服务器端

JQuery 代码:

<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 代码:

<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" />

在您的服务器端 PHP 代码(这里我将发布到服务器的内容发回,仅作为示例)

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

【讨论】:

  • 感谢@Swarnajith 的帮助。
【解决方案2】:

convert a HTML table data into a JSON object in jQuery 可能重复

但解决方案是

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

然后只需使用 $.json(或您想要的任何库)将其转换为 JSON 字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2021-11-11
    相关资源
    最近更新 更多