[英]Get HTML's <TD> Value
我想從我的表數據(標記)中獲取靜態值,並將其顯示在另一頁上。 我應該為此使用jQuery還是可能使用PHP?
Example.php表:
<table width="100%" class="table table-striped table-bordered table-hover display" id="dataTables-example">
<thead>
<tr>
<th>Race</th>
<th>Role</th>
<th>2015</th>
<th>2016</th>
<th>2017</th>
</tr>
</thead>
<tbody>
<tr class="Testing">
<td>BLAH</td>
<td>ANOTHA_BLAH</td>
<td>25</td>
<td>26</td>
<td>27</td>
</tr>
</table>
我嘗試用類似於
<form action = "PutTheExampleTableValuesHere.php" method = "post">
TABLE BLAH BLAH BLAH
<input type="submit" name="submit" value="View Line Chart">
並使用$ _POST函數並將其簡單地回顯到其他頁面,但是我的邏輯失敗了。
請指導。 謝謝!
您可以使用AJAX將整個html代碼發布到另一頁( URL
):
$.post(URL, {data: encodeURIComponent($("#dataTables-example").html())})
在另一個頁面( URL
)上,可以使用php的$_POST
來獲取它:
<form action = "PutTheExampleTableValuesHere.php" method = "post">
<table ...>
<?php urldecode($_POST['data']) ?>
</table>
<input type="submit" name="submit" value="View Line Chart">
更新:
@SimoneWalter然后,您可以將$.post
的data
與TD值組成。 例如:
data = []
$.each($("#dataTables-example TR"), function(tr){
// get td values
tmp = []
$.each($(tr).find('TD'), function(td){
tmp.push($(td).html())
})
data.push(tmp)
})
// post the data
// data will be something like:
// [['Race', 'Role', '2015', ...], ...]
$.post(URL, {data: data})
然后在另一頁上:
<form action = "PutTheExampleTableValuesHere.php" method = "post">
<table ...>
<thead>
<?php foreach($_POST['data'] as $tr): ?>
<tr>
<?php foreach($tr as $td): ?>
<td><?php echo $td ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</thead>
</table>
<input type="submit" name="submit" value="View Line Chart">
與$ _POST邏輯相比,此解決方案比使用javascript / ajax更簡單。 只需將數據放在某個段落或類似的段落中並給它起一個名字,這樣您就可以從另一個外部頁面(在表單中以“ method”參數調用)訪問該數據。 例:
index.php:
<form action="test.php" method="post">
<table>
<td>
<div id="blah" name="blah" value="blah">BLAH</div>
</td>
<td>
<div id="anoblah" name="anoblah" value="anotherblah">BLAH</div>
</td>
<input type="submit" id="test" name="test">
</table>
</form>
test.php
<?php
if(isset($_POST["test"]))
echo "td1: ".$_POST["blah"]." td2: ".$_POST["anoblah"];
?>
您可能可以使用jquery在表單結構中創建一個數組(使用隱藏的輸入)。 然后,您可以在提交表單后使用$ _POST變量讀取它。
<script>
$(document).ready(function(){
$("input[type=submit]").click(function(e) {
e.preventDefault();
var form = $("form");
$(".Testing td").each(function() {
form.append('<input type="hidden" name="data[]" value="' + $(this).html() + '">');
});
form.submit();
});
});
</script>
這將從“ Testing”類下的TD值創建一個數組,您可以通過$ _POST ['data'](類型Array)進行訪問。
<?php
if(isset($_POST['data'])) {
foreach($_POST['data'] as $key=>$val) {
echo $key.' = '.$val.'<br>';
}
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.