当 csrf 设置为自动时,如何使用带有 codeigniter 4 的 jquery 验证库检查现有数据?

How to check existing data with jquery validation library with codeigniter 4 when csrf is set to auto?

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

//我的路由器

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

提前致谢。

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

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

和returns:

a string containing the JSON representation of the supplied value.

在您的控制器函数 check_category() 中,您正在发送 $status,而 $data 正在设置无效标志:

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

$status = true;改为$data['status'] = true;

并且只回显状态和 csrf 哈希

echo json_encode($data);  // correct

经过如此多的努力,我终于找到了解决问题的方法。现在我可以使用 dataFilter 对象更新 csrf 令牌并在 ajax 调用期间摆脱错误 403。 这是我对我的控制器所做的,即使我通过从 db 直接获取数据到控制器来破坏 Mvc 原则。 我知道这不是我所做的最好的方法,如果有任何建议,请纠正我,我将不胜感激。谢谢!

//我的控制器方法

    public function check_category()
    {
        $name = $this->request->getPost('name');
        $query = $this->db->table('categories')->where(['cat_name' => $name])->countAllResults();
        
        $valid = true;
        if($query > 0){
            $valid = false;
        }else{
            $valid = true;
        }
        $csrf = csrf_hash();
        return $this->response->setJSON(['valid'=>$valid, 'csrf'=>$csrf]);
    }

//我的javascript

    $('#create_category').validate({
          onkeyup: false,
          rules: {
              name: {
                  required: true,
                  remote: {
                      url: 'check-category',
                      type: 'post',
                      dataType:'json',
                      dataFilter: function(data){
                          let obj = eval('('+data+')');
                          $('input[name="csrf_hash_name"]').val(obj.csrf);
                          return obj.valid;
                      },
                      data:{ csrf_hash_name: function(){ return $('input[name="csrf_hash_name"]').val(); } }
                  }
              }
          },
          messages: {
              name: {
                  required: "Enter a Category.",
                  remote: "{0} This category exists."
              }
          },
          submitHandler: function(form) {
              return false;
        }
      });