我有一个jquery脚本正在为表生成内容,我想知道如何使用ajax和php一次将该表上所有添加的行保存到数据库。
即时通讯使用dataTable。
示例表:http://i38.photobucket.com/albums/e149/eloginko/table_zps20bbecb1.png
这就是我的表格:http://jsfiddle.net/4GP2h/104/
我的剧本:
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
autoOpen: false,
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
var dataSet;
try{
dataSet = JSON.parse(localStorage.getItem('dataSet')) || [];
} catch (err) {
dataSet = [];
}
$('#myTable').dataTable({
"data": [],
"columns": [{
"title": "Name"
}, {
"title": "Age"
}, {
"title": "Gender"
}, {
"title": "Action"
}],
"bStateSave": true,
"stateSave": true,
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"bInfo": false,
"bAutoWidth": false
});
oTable = $('#myTable').DataTable();
for (var i = 0; i < dataSet.length; i++) {
oTable.row.add(dataSet[i]).draw();
}
$('#Save').click(function () {
if ($('#name').val() == '' || $('#age').val() == '' || $("input[name='gender']:checked").val() == undefined) {
$("#dialog-confirm").dialog("open");
} else {
var data = [
$('#name').val(),
$('#age').val(),
$("[name='gender']:checked").val(),
"<button class='delete'>Delete</button>"
];
oTable.row.add(data).draw();
dataSet.push(data);
localStorage.setItem('dataSet', JSON.stringify(dataSet));
}
});
$(document).on('click', '.delete', function () {
var row = $(this).closest('tr');
oTable.row(row).remove().draw();
var rowElements = row.find("td");
for (var i = 0; i < dataSet.length; i++) {
var equals = true;
for (var j = 0; j < 3; j++) {
if (dataSet[i][j] != rowElements[j].innerHTML) {
equals = false;
break;
}
}
if (equals) {
dataSet.splice(i, 1);
break;
}
}
localStorage.setItem('dataSet', JSON.stringify(dataSet));
});
答案 0 :(得分:0)
在代码中添加表单标记:
<form id='myform'>
<div id="dialog-confirm" title="Error">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 0px 0;"></span>Please fill all the required fields!</p>
</div>
<br />
<br />Name:
<input type="text" name="name" id="name" />
<br />Age:
<input type="text" name="age" id="age" />
<br />Gender:
<input type="radio" name="gender" value="Male" />Male
<br />
<input type="radio" name="gender" value="Female" />Female
<br />
<button id="Save" name="Save">Save</button>
<div class="container well">
<table id="myTable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<tr>
<td>
Line 1 Edit
</td>
<td>
<input type='text' name='line1' />
</td>
</tr>
<tr>
<td>
Line 2 Edit
</td>
<td>
<input type='text' name='line2' />
</td>
</tr>
</table>
</div>
</form>
然后您可以使用jquery将其发送到您的服务器
var formdata = $("#myform").serialize()
formdata
会将表单中的数据放入变量中,以便为post或get请求做好准备。
然后使用$.post("myurl?" + formdata, function(response_from_server){alert(response_from_server);})