【发布时间】:2019-02-18 06:47:56
【问题描述】:
我使用 JavaScript 动态创建了一个 HTML 表格。
所以,行数不是固定的。如果我单击添加行按钮,它将生成一个新行。以下 HTML 和 JavaScript 代码将生成动态表格。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
var actions = $("table td:last-child").html();
// Append table with add row form on add new button click
$(".add_new").click(function(){
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="text" name="fname" class="form-control" ></td>' +
'<td><input type="text" name="lname" class="form-control" ></td>' +
'</tr>';
$("table").append(row);
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function(){
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function(){
if(!$(this).val()){
$(this).addClass("error");
empty = true;
} else{
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if(!empty){
input.each(function(){
$(this).parent("td").html($(this).val());
});
}
});
// Delete row on delete button click
$(document).on("click", ".delete", function(){
$(this).parents("tr").remove();
$(".add_new").removeAttr("disabled");
});
});
</script>
</head>
<body>
<form action="display_table.php" id="my_form" name="my_form" method="post" >
<table id='userTable' name='userTable'>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="fname"></td>
<td><input type="text" name="lname"></td>
</tr>
</tbody>
</table>
<input type="button" id="add_new" name="add_new" class="add_new" value="Add New Row" >
<input type="submit" name="save" value="Submit">
</form>
</body>
</html>
现在,如果我点击提交按钮,那么应该将表格数据发送到 display_table.php 页面。
display_table.php
<?php
$user_table=$_POST['userTable'];
echo $user_table;
#Next task is to process the table and store into MySQL Database
?>
如果表格数据被接收到 display_table.php 然后我将处理数据存储到 MySQL 数据库中。
我需要帮助将 HTML-JavaScript 表格发送到 display_table.php
【问题讨论】:
-
$_POST['userTable']将不存在,因为没有具有该名称的表单元素。未发布表格,因为它不是有效的表单元素。您需要访问输入字段:$_POST['fname']等。此外,如果您添加多个具有相同名称的输入,您需要通过命名它们将它们作为数组传递:name="fname[]"(注意名称后面的[])。然后$_POST['fname']将是一个数组,其中包含具有该名称的所有输入。 -
你的意思是,如果我像
<td><input type="text" name="fname[]"></td>这样更改 HTML 代码,如果我像<?php $fname=$_POST['fname']; ?>这样更改 PHP 代码,那么在 PHP 代码中,变量$fname是一个数组? -
是的,没错。
-
是的。我明白了。现在它起作用了。谢谢。
标签: javascript php jquery html ajax