【发布时间】:2015-06-04 05:05:07
【问题描述】:
我正在使用 Codeigniter,在通过 ajax 在数据库中插入值时遇到问题。 当 sql 查询抛出错误时会出现问题。 这是我的控制器代码:-
public function Register_data()
{
$data = array(
'user_name'=>$this->input->post('name'),
'user_email'=>$this->input->post('emailid'),
'user_pwd'=>$this->input->post('pwd'),
'user_pno'=>$this->input->post('pno'),
'user_gender'=>$this->input->post('gender'),
'user_age'=>$this->input->post('age'),
'dor'=>date('Y-m-d H:i:s'),);
$this->load->model('Register');
$this->Register->insert_content($data);
$output = array(); //Creating output array for json response to ajax
$output['result'] = $this->Register->getStatus(); echo $output['result'].'---';
$output['message'] = $this->Register->getMessage(); echo $output['message'];
echo json_encode($output);
}
我的模型代码是这样的:-
class Register extends CI_Model{
var $message;
var $status;
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function insert_content($da)
{
if ($this->db->insert('user',$da))//Checking if mysql query is successful
{
$this->status = true;
$this->message = "DATA INSERTED";
}
else
{
$this->status = false;
$this->message = $this->db->error_message();
}
}
public function getStatus()
{
return $this->status;
}
public function getMessage()
{
return $this->message;
}}
这是我的 Ajax 调用:-
$.ajax({
url: "<?php echo site_url('Home_Controller/Register_data');?>",
data: $("#frm").serialize(),
type: 'POST',
success: function (data) {
alert(data);
var resp = $.parseJSON(data);
if (resp.result) {
window.location.href = "<?php echo site_url('Home_Controller');?>";
} else {
$("#msgs").html(resp.message);
}
},
error: function (error) {
$("#msgs").html(JSON.stringify(error)); //This is returned when model condition for inserting data throws error.
}
});
请注意,正在插入数据。因此插入时没有问题。我已经使用 json 作为对 ajax 的响应返回。只有在插入出错时才会出现问题。示例:-我在数据库中保持电子邮件是唯一的,因此当我在数据库中插入重复项时,mysql 会抛出一个错误,提示重复错误,因为你可以在模型中看到我的代码,我在 if 条件下插入代码,并且在插入查询时获取失败状态和 msg 存储在变量中。这就是我过去在核心 php 中所做的事情。我不知道如何在 codeigniter 中处理这个问题。请提供一个好的解决方案。任何帮助将不胜感激。
【问题讨论】:
-
检查这个链接...它可能对你有帮助stackoverflow.com/questions/1893381/…
-
Thanx Ashwani,因为你的帖子,我已经解决了这个问题
标签: javascript php jquery ajax codeigniter