javascript - 当 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; }
});
提前致谢。
解决方案
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
推荐阅读
- android - Firestore 检索嵌套对象并转换为 POJO
- javascript - 请用javascript解释原型
- c# - 加载到 DataTable 时 NullValues 选项不起作用
- sql-server - 为什么 FORMAT 不能与 expandproperty 一起使用
- favicon - 如何修复我在 Chrome 的 Web 开发人员工具中使用 Lighthouse 收到的 manifest.json 错误?
- .net - 如何使用 Mono WebAssembly 在浏览器中运行简单的 .NET 方法?
- apache-kafka - 用于从 csv 读取并转换为 avro 的 kafka 连接器
- package - 如何处理 Racket 中的名称冲突?
- facebook-graph-api - 发布到我使用 Graph API 管理的 Facebook 页面
- java - 我对包含不同数字的整数数组的所有排列的解决方案的时间复杂度