我正在尝试制作一个表格,我可以在其中通过单击按钮添加新行,然后将表格发送到服务器,以便它记住页面刷新时的信息。下面是一个按钮,它成功地将一行添加到具有当前时间的表中。但是,当我通过“发送到服务器”按钮将表格发送到服务器时,它不会回显更新后的表格,只会回显原始表格。弄清楚这个问题真是令人欣慰。
HTML:
<input type = "button" id = "send" value = "Send to Server" />
<input type = "button" id = "add" value = "Add Row" />
<table class="table table-striped">
<tr>
<td><h2>In</h2></td>
<td><h2>Out</h2></td>
<td><h2>Total</h2></td>
</tr>
<tr>
<td>InData</td>
<td>OutData</td>
<td>TotalData</td>
</tr>
</table>
JS:
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">
$("#add").click(function(){
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds(); //set variable to current time
$('table > tbody:last').append('<tr><td>'+time+'</td><td></td><td></td></tr>'); //add row to table with current time
});
$(function(){
var dataArr = [];
$("table").each(function(){
dataArr.push($(this).html());
});
$('#send').click(function(){
$.ajax({
type : "POST",
url : 'timesheet.php',
data : "content="+dataArr,
success: function(data) {
alert(data);// alert the data from the server
},
error : function() {
}
});
});
});
</script
PHP(时间表.php):
<?php
echo $_REQUEST['content'];
?>
最佳答案
when I send the table to the server via the "Send to Server" button it does not echo back the updated table, only the original.
解决方案
使用 .on()
代替 .click()
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">
$(document).on('click', '#add', function(){
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds(); //set variable to current time
$('table > tbody:last').append('<tr><td>'+time+'</td><td></td><td></td></tr>'); //add row to table with current time
});
$(document).on('click', '#send', function(){
var dataArr = [];
$("table").each(function(){
dataArr.push($(this).html());
});
$('#send').click(function(){
$.ajax({
type : "POST",
url : 'timesheet.php',
data : "content="+dataArr,
success: function(data) {
alert(data);// alert the data from the server
},
error : function() {
}
});
});
});
</script>
已编辑:
您正在使用的 click()
绑定(bind)称为“直接”绑定(bind),它只会将处理程序附加到已经存在 的元素。它不会绑定(bind)到将来创建的元素。为此,您必须使用 on()
创建一个“委托(delegate)”绑定(bind)。
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
关于javascript - 将行添加到表并发送到服务器,通过 jquery 将表发布到 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33833780/