将动态创建的行中的数据保存到数据库中 [英] Save data from dynamically created rows to database
问题描述
我正在使用Codeigniter.我创建了一个包含不同列的表.我想在单击"+"按钮时动态创建行.现在,我能够使用jquery创建行.我想将数据保存到数据库.单击"+"按钮时如何将每一行的值保存到数据库中?
I am using Codeigniter. I have created a table that contains different columns. I wanted to create rows dynamically when clicking on the '+' button. Now i am able to create rows using jquery. I want to save the data to database. how can i save the values of each rows to database when i click on the '+' button?
推荐答案
您可以对此使用ajax请求.
You can use ajax request on this.
首先,当您单击+
按钮时,不仅可以在每一列中输入文本,还可以放置输入字段.
First when you click +
button, instead of just text in each column, you can put input fields.
<tr>
<td><input id="field1" type="text" /></td>
<td><input id="field2" type="text" /></td>
<td><input id="field3" type="text" /></td>
<td><button id="save"></button></td>
<tr>
之后,您可以将事件分配给button#save
.单击时,它将从字段中获取所有输入,然后将其存储在变量中并调用ajax请求.您应该准备一个php代码来处理此请求.
After that, you can assign an event to the button#save
. When it is click, it will get all the inputs from the fields then store in variable and call an ajax request. You should prepare a php code to handle this request.
$('#save').on('click', function() {
var data = {
field1: $('input#field1').val(),
field2: $('input#field2').val(),
field3: $('input#field3').val()
};
// call ajax request
$.post(url + '/controller/save', data, function(data) {
console.log(data);
});
}
在您的controller
中,您应该具有处理请求的save
方法.
In your controller
you should have that save
method that handle the request.
public function save() {
if($_POST) {
// get input
// call model to save data to db
}
}
此处更新
您可以保存按钮以保存所有数据.
Updated Here
You can have a button save to save all the data.
$('#save').click(function() {
var data = $('input').serialize();
$.post(url, data, function(data) {
console.log(data);
});
});
然后只需使用print_r
或var_dump
即可在控制器中的方法中查看发布的值.
Then just use print_r
or var_dump
to see the posted values in your method in controller.
这篇关于将动态创建的行中的数据保存到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!