jQuery表格添加数据并Ajax提交数据
阅读目录
- 实现效果
- HTML
- php
实现效果
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<style>
#mform{
margin: 10px; }
#mtable{
border-collapse: collapse; }
#mtable thead th,#mtable thead td{
min-width: 120px; }
#mdiv{
display: none; }
</style>
姓名:<input type="text" name="name" value="">
学历:<input type="text" name="education" value="">
年龄:<input type="text" name="age" value="">
<input id="add" type="button" value="添加"><br>
<form id="mform" action="" method="post">
<table id="mtable" border="1">
<thead>
<tr>
<th>姓名</th>
<th>学历</th>
<th>年龄</th>
</tr>
</thead>
<tbody id="mtbody">
</tbody>
</table>
<div id="mdiv"></div>
<input id="sub" type="button" value="提交"><br>
</form>
<script>
$(function(){
//添加tr
$('#add').click(function(){
var name = $("input[name='name']").val();
var education = $("input[name='education']").val();
var age = $("input[name='age']").val();
var html = '';
html += '<tr>';
html += '<td class="name">'+name+'</td>';
html += '<td class="education">'+education+'</td>';
html += '<td class="age">'+age+'</td>';
html += '</tr>';
$('#mtbody').append(html);
});
//提交
$('#sub').click(function(){
$('#mdiv').html('');
$.each($('#mtbody tr'),function(k){
var name = $('.name', this).text();
var education = $('.education', this).text();
var age = $('.age', this).text();
var html = '';
html += '<input type="text" name="data[' + k + '][name]" value="' + name + '">';
html += '<input type="text" name="data[' + k + '][education]" value="' + education + '">';
html += '<input type="text" name="data[' + k + '][age]" value="' + age + '"><br>';
$('#mdiv').append(html);
});
var data = $("#mform").serialize();
$.ajax({
type: "POST",
data: data,
url: "http://example.com/api/excel_import_export",
dataType: 'json',
success: function (json) {
}
});
});
});
</script>
</body>
</html>
php
<?php
echo '<pre>';
print_r($_POST);
/*
结果为:
array:2 [
"data" => array:2 [
0 => array:3 [
"name" => "wgchen"
"education" => "撒"
"age" => "都是"
]
1 => array:3 [
"name" => "wgchen阿萨德"
"education" => "撒阿萨德"
"age" => "都是阿萨德"
]
]
"s" => "/api/excel_import_export"
]
*/
还没有评论,来说两句吧...