【问题标题】:Codeigniter API, Database Error Request Returns Object instead of set responseCodeigniter API,数据库错误请求返回对象而不是设置响应
【发布时间】:2019-09-17 13:49:21
【问题描述】:

我在 codeigniter 上使用 rest api 时遇到问题,我的 api 控制器上有以下代码:

public function index_post()

{

    $input = $this->input->post();
    $data = array();

    try {
        $this->db->insert('attorneys', $input);
        $data = array('id' => $this->db->insert_id(), 
                      'message' => 'Attorney has been added'); 

        $this->response($data, REST_Controller::HTTP_OK);
    } catch (Exception $e) {
        $data = array('error_number' => $this->db->_error_number());
        $this->response($data, REST_Controller::HTTP_OK);
    }
} 

当我在数据库中遇到重复条目时收到错误,因为字段设置为唯一,我收到一个对象作为来自我的 ajax 发布请求的响应:

$.ajax({
                type: "POST",
                url: "/"+location.pathname.split('/')[1]+"/api/attorneys",
                data: data,
                dataType: "json",
                success: function(data)
                {   
                    console.log('success');
                    console.log(data);
                    $("#attorneyList").append('<div class="list-info">'+
                                                '<label><b>'+$('#inputAttorneyName').val()+'</b></label><br>'+
                                                '<label>Law Office: <span>'+$('#inputLawOffice').val()+'</span></label><br>'+
                                                '<label>Phone: <span>'+$('#inputAttorneyPhone').val()+'</span></label><br>'+
                                                '<label>Email: <span>'+$('#inputAttorneyEmail').val()+'</span></label><br>'+
                                              '</div>'); 
                    $('#attorneyIDs').val($('#attorneyIDs').val()+data.id+",");
                    $('#addAttorneyModal').modal('hide');
                },
                error: function(data) {
                    console.log('error');
                    console.log(data);
                }
            });

我的 console.log 返回这个对象:

【问题讨论】:

    标签: ajax rest api codeigniter


    【解决方案1】:

    如果您仔细查看 responseText,您会发现返回的是错误页面。该错误是因为您尝试在很可能需要唯一值的字段中插入重复值。在这种情况下,“名称”列已经包含值“Lawrence Boadilla”。

    在尝试插入之前,您需要进行一些验证以检查这些条件。

    try 块没有帮助,因为 CodeIgniter 不会从数据库类中抛出异常。

    同样,您无法检查来自$this-&gt;db-&gt;insert() 的返回,因为错误意味着insert() 不会返回,而是会停止脚本执行。至少在您打开错误报告时是这样。

    【讨论】:

    • 没有其他选择了吗?
    猜你喜欢
    • 2017-02-17
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2021-05-21
    • 2018-05-03
    • 2020-08-08
    相关资源
    最近更新 更多