从html中的表中提取数据?

时间:2017-07-13 05:16:45

标签: javascript jquery html

从不包含<form>或任何<input>元素的html页面向后端应用程序发送数据是否被视为不良做法?

基本上,我有一种情况,我必须从html页面获取一些数据,将其传递给后端应用程序,处理它然后返回一些结果数据。通常情况下,我会有一些html表单来提取数据...但是,在我的情况下,我只是一张桌子而已。此外,<table><tr><td>元素没有任何id。从html表单中提取数据以使用javascript发回的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

这里我在click事件中获取表行值。您可以使用ajax post将它们传递给服务器。

<!DOCTYPE html>
<html>
<body>
    <table>
    <thead>
        <th>Firstname</th>
        <th>Lastname</th> 
        <th>Age</th>
    </thead>
    <tbody>
        <tr>
            <td>Jill</td>
            <td>Smith</td>
            <td>50</td>
        </tr>
        <tr>
            <td>Eve</td>
            <td>Jackson</td>
            <td>94</td>
        </tr>
        <tr>
            <td>John</td>
            <td>Doe</td>
            <td>80</td>
        </tr>
    </tbody>
    </table>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("table tbody tr").on("click",function(e){
                var rowValue = $(this).context.innerText.split("\t");
                alert(rowValue);
            });
        });
    </script>
</body>
</html>

答案 1 :(得分:0)

您可以创建一个对象数组,每个对象都有一个列的索引,其值设置为内部文本列。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>R1:C1</td>
    <td>R1:C2</td>
    <td>R1:C2</td>
  </tr>
  <tr>
    <td>R2:C1</td>
    <td>R2:C2</td>
    <td>R2:C2</td>
  </tr>
  <tr>
    <td>R3:C1</td>
    <td>R3:C2</td>
    <td>R3:C2</td>
  </tr>
  <tr>
    <td>R3:C1</td>
    <td>R3:C2</td>
    <td>R3:C2</td>
  </tr>
</table>
<script>
var data=[];
$('table tr').each(function(i ,e) 
{
  var row={};
  $(e).find("td").each(function(n,k) {
    row[n]=$(k).text();
  })
  data.push(row);
});
console.log(data);
//Result
/*
[
  {
"0": "R1:C1",
"1": "R1:C2",
"2": "R1:C2"
  },
  {
"0": "R2:C1",
"1": "R2:C2",
"2": "R2:C2"
  },
  {
"0": "R3:C1",
"1": "R3:C2",
"2": "R3:C2"
  },
  {
"0": "R3:C1",
"1": "R3:C2",
"2": "R3:C2"
  }
]
*/
</script>