首页 > 解决方案 > 当 csrf 设置为 auto 时,如何使用带有 codeigniter 4 的 jquery 验证库检查现有数据?

问题描述

我有一个表单,我正在尝试使用 jquery 验证插件和 codeigniter 4 进行验证,我已经启用了设置为为每个请求自动生成的 csrf。我能够在第一次请求时获得验证状态,但是当我尝试另一个请求时,我得到错误 403,当我将第二个参数设置为 json_encode() 时,我得到错误 500。我希望能够在每次请求 ajax 调用后更新 csrf .

//我的路由器

  $routes->post('check-category', 'Admin\Category::check_category');

//我的控制器

//check if category name exist
    public function check_category()
    {
        $name = $this->request->getPost('name');
        $query = $this->db->table('categories')
                          ->where(['cat_name' => $name])
                          ->get()
                          ->getResult();
        
        $status = true;
        if(count($query) > 1){
            $status = false;
        }else{
            $status = true;
        }
        $data['csrf'] = csrf_hash();
        echo json_encode($status, $data);
    }

// javascript

    $('#create_category').validate({
        onkeyup: false,
        rules: {
            name: {
                remote: {
                    url: 'check-category',
                    type: "post",
                    data:{
                        csrf_hash_name: function(){
                           return $('input[name="csrf_hash_name"]').val();
                        }
                    },
                    complete: function(data){
                       $('input[name="csrf_hash_name"]').val(data.csrf);
                    }
                }
            }
        },
        messages: {
            name: {remote: "This category exists."}
        },
        submitHandler: function(form) { return false; }
    });

提前致谢。

标签: javascriptphpjqueryajaxcodeigniter

解决方案


php 函数json_encode()的结构如下所示:

json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|false

并返回:

包含所提供值的 JSON 表示形式的字符串。

check_category()在您发送的控制器功能中$status,同时$data设置无效标志:

echo json_encode($status, $data);  // wrong

变成; $status = true;_$data['status'] = true

并且只回显状态和 csrf 哈希

echo json_encode($data);  // correct

推荐阅读