【问题标题】:POST'ing JSON with Codeigniter returns a 500 error使用 Codeigniter 发布 JSON 返回 500 错误
【发布时间】:2011-07-18 18:13:04
【问题描述】:

我在使用 ajax 发布函数从控制器返回数据时遇到问题。这里发生的是用户将输入一个样式编号,将该编号提交给控制器。控制器获取提交的值,查询数据库并将结果返回给控制器,然后控制器返回一个数组,然后我将其编码为 json。但我不断收到 500 内部服务器错误???

这是我的控制器

//return schools based on style id
public function search() {
    $input = json_decode($this->input->post('obj'));
    $style_id = $input['style_id'];
    $parent_id = $input['parent_id'];
    $data = array();
    if ($q = $this->page_model->search_results($style_id, $parent_id)) {
        $data = $q;
    }
    echo json_encode($data);
}

这是我的模型

//get all entries
function search_results($style_id, $parent_id) {
    $options = array(
        'Style' => $style_id,
        'Parent_ID' => $parent_id
    );
    $this->db->select('*');
    $this->db->from('pages');
    $this->db->join('entry', 'pages.Page_ID = entry.Parent_Page_ID', 'inner');
    $this->db->where($options);
    $q = $this->db->get();

    if ($q->num_rows() > 0) {
        return $q->result();
    }

}

这是我的 javascript

//dress style search
$($searchBtn).click(function(event) {
    var style_id,
         parent_id,
         obj = {};
    //get the value of the input fields
    searchVal = event.currentTarget.previousSibling.value;
    parentID = event.currentTarget.parentElement.childNodes[3].value;
    //The object to be passed to the controller
    obj = { 'style_id' : searchVal, 'parent_id' : parentID };
    //POST the values in json notation, return the search results in json notation
    $.post(base_url + 'index.php/page/search',
            obj,
            function(data) {
                console.log(data);
            },
            'json');
    return false;
});

base_url=http://localhost:8888/lexsreg

顺便说一句 - 如果我注释掉 return false,我会得到一个从我的控制器回显的 json 字符串。

提前致谢!

【问题讨论】:

    标签: javascript jquery ajax json codeigniter


    【解决方案1】:

    您必须包含 csrf 令牌。如这两个博客中所述,有几种方法可以做到这一点。

    http://aymsystems.com/ajax-csrf-protection-codeigniter-20

    http://codeigniter.com/forums/viewthread/176318/

    【讨论】:

    • 在 CI 2.0.3 版本中,csrf 令牌的名称再次更改,此版本的名称为“csrf_test_name”
    【解决方案2】:

    好吧,第一步是确保您已加载page_model。然后我会确保你在 where 子句中得到了正确的列——你需要通过<table-name>. 来识别这些列吗?

    然后基本的 CI 调试从 log_message 开始:调用 log_message('DEBUG', $this->input->post('obj')); 后跟 log_message('DEBUG', json_decode($this->input->post('obj')));

    【讨论】:

    • 我正在自动加载我的模型,不知道 log_message 功能,我会尝试一下 thxs
    • 发现我必须包含 csrf 令牌...d'oh!
    猜你喜欢
    • 2015-05-27
    • 2016-03-10
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 2014-06-26
    相关资源
    最近更新 更多