我有一个表格,可以使用 ajax 插入到表“标签”中。我可以手动添加,但必须重新加载页面。
这是我的控制器控制器(tags.php)
class Tags extends CI_Controller{
function __construct(){
parent:: __construct();
$this->load->model('tags_model');
$this->load->helper('form');
$this->load->helper('url');
}
function index(){
$data['tags']=$this->tags_model->get();
$this->load->view('tags/index',$data);
}
function add()
{
$this->tags_model->save();
return true;
}
}
?>
这是我的观点('index.php')
<script src="<?php echo base_url('assets/js/jquery.js');?>"></script>
<?php
foreach ($tags as $t){
echo '<span>';
echo $t['id'].':';
echo $t['title'];
echo '-';
echo '</span>';
}
?>
<form id="comment" method="post">
<?php echo form_input('title','text is here....');?>
<label> </label><input type="submit" value="Submit" />
</form>
<!-- here is the script that will do the ajax. It is triggered when the form is submitted -->
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tags/add",
data: dataString,
return false; //stop the actual form post !important!
success: function(data)
{
alert('Successful!');
}
});
return false; //stop the actual form post !important!
});
});
</script>
模型
<?php
class Tags_model extends CI_Model{
function __construct()
{
parent:: __construct();
$this->load->database();
}
function save()
{
$title=$this->input->post('title');
$data=array(
'title'=>$title
);
$this->db->insert('tags',$data);
}
function get(){
$query=$this->db->get('tags');
return $query->result_array();
}
}
?>
代码对我来说似乎没问题。我可以正常插入,但不能在 ajax 中插入。欢迎任何帮助。