javascript - 当 sql 返回错误时,Jquery Ajax 显示错误 500

标签 javascript php jquery ajax codeigniter

我正在使用 Codeigniter,通过 ajax 在数据库中插入值时遇到问题。 当sql查询抛出错误时就会出现问题。 这是我的 Controller 代码:-

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.
    }
});

Red Color text is an error which is displayed when sql duplication occurs

请注意,数据正在被插入。因此插入时没有问题。我使用 json 作为对 ajax 的响应返回。仅当插入出错时才会出现问题。示例:- 我将电子邮件在数据库中保留为唯一,因此当我在数据库中插入重复项时,mysql 会抛出一个错误,指出重复错误,因为您可以在模型中看到我的代码,我在 if 条件中插入了代码,并且在插入查询时插入了代码获取失败状态并将消息存储在变量中。这就是我以前在核心 php 中所做的事情。我不知道如何在 codeigniter 中处理这个问题。请提供好的解决方案。任何帮助将不胜感激。

最佳答案

Codeigniter 包含了 error() 函数来显示数据库错误。 db->e​​rror_message() 是听到的问题

关于javascript - 当 sql 返回错误时,Jquery Ajax 显示错误 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30635300/

相关文章:

javascript - 选择的 ID 丢失

java - JSP 中的 ItemEvent 等效项

javascript - ng-include 包含在 ng-include 中,两者都绑定(bind)到不同的 Controller

php - PHP验证YouTube脚本

php - Laravel 文件路径

javascript - 如何在不同的事件上激活这个 JQuery?

javascript - 有什么方法可以使用 velocity js 将渐变颜色应用于文本?

javascript - 使用 jquery 添加/删除类但不重绘元素以反射(reflect)

php - 使用 PHP 从任何选择查询中提取表名

javascript - 我的 jQuery slider 无法正常工作