作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试将此表单中的数据发布到数据库中。我尝试了一些教程但没有成功。这是我的代码。有什么想法吗?
查看:
<form method="post" name="myForm1" id="myForm1" enctype="multipart/form-data" >
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="submitbutton" type="submit">
</form>
AJAX(在 View 中,在表单的正下方)
<script type='text/javascript' language='javascript'>
$("#submitbutton").click(function(){
$.ajax({
url:'http://localhost:8888/index.php/trial/insert_into_db',
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
},
error: function(){
alert("Fail")
}
});
e.preventDefault();
});
</script>
Controller
function insert_into_db(){
$this->load->model('insert_db');
$this->insert_db->insertQ();
}
模型
class Insert_db extends CI_Model{
function insertQ(){
$email = $_POST['email'];
$qText = $_POST['qText'];
$this->db->query("INSERT INTO questions VALUES('','$email','$qText','','')");
}
}
最佳答案
正如@David Knipe 所说,您应该等待 DOM 准备就绪,然后再尝试访问其元素之一。此外,您可能有一个 e
is undefined 错误,因为您没有将事件引用传递给点击处理程序:
<script> //no need to specify the language
$(function(){
$("#submitbutton").click(function(e){ // passing down the event
$.ajax({
url:'http://localhost:8888/index.php/trial/insert_into_db',
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
$('#email').val('');
$('#qText').val('');
},
error: function(){
alert("Fail")
}
});
e.preventDefault(); // could also use: return false;
});
});
</script>
更完整地说,您的查询很容易受到攻击,您可能会在那里遇到错误。利用在您下方拥有框架的优势:
function insertQ(){
$email = $this->input->post('email');
$qText = $this->input->post('qText');
$this->db->insert('questions', array('email' =>$email, 'text' => $text));
}
^_
我猜是列名,因为你没有指定它们
关于php - 使用 Codeigniter 使用 AJAX 和 jquery 将表单数据传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21004315/
我是一名优秀的程序员,十分优秀!