且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 Codeigniter 中的 CSRF 包含到 ajax 数据中

更新时间:2022-05-11 01:38:29

token需要传入$.ajaxdata参数中.

The token needs to be passed in the data argument of $.ajax.

这应该可行,但请参阅下面的注释.

This should work but see my notes below.

order['security->get_csrf_token_name();?>'] = '<?php echo $this->security->get_csrf_hash();?>';

但是,这里有一些不好的做法.主要是您不应该在您的 javascript 中使用 PHP,因为这会阻止您将 javascript 作为单独的文件访问(这很好,因为浏览器会缓存它以使您的页面加载速度更快并消耗更少的带宽).

However, there are a few bad practices going on here. Mainly you should not use PHP in your javascript because this prevents you from being able to access the javascript as a separate file (this is good because browsers will cache it to make your page load faster and consume less bandwidth).

***将令牌存储在您的订单

html 中,就像这样..

It's better to store the token in your order <form> html like this..

<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>"value="<?php echo $this->security->get_csrf_hash(); ?>"/>

然后它将与您的表单数据的其余部分一起序列化.

Then it will get serialized with the rest of your form data.

您还可以将 URL 存储在表单的 action 属性中.这将有助于您的脚本优雅地降级,并将 URL 保留在一个位置而不是 2 个位置.

You can also store the URL in the form's action attribute. This will help your script gracefully degrade and also keeps the URL in one place instead of 2.

<form id="order" method="post" action="<?=base_url()?>admin/category/update_order">

$.ajax 调用中,使用类似这样的 url: $('#order').attr('action'), 假设 #order 是实际表单 ID.

In the $.ajax call, use something like this url: $('#order').attr('action'), assuming #order is the actual form id.