如何将 Codeigniter 中的 CSRF 包含到 ajax 数据中 [英] How to include CSRF from Codeigniter into ajax data

查看:24
本文介绍了如何将 Codeigniter 中的 CSRF 包含到 ajax 数据中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些数据传递到我的控制器中,但出现 500 错误.经过一番研究,发现是CSRF token没有发送造成的.

I am trying to pass some data into my Controller, but I'm getting a 500 error. After some research, I discovered that it's caused by the CSRF token not being sent.

似乎我需要将其与数据一起包含在内:<?php echo $this->security->get_csrf_token_name();?>:"<?php echo $this->security->get_csrf_hash(); ?>"

It seems like I need to include this along with the data: <?php echo $this->security->get_csrf_token_name(); ?>:"<?php echo $this->security->get_csrf_hash(); ?>"

我的 JS 很弱,所以我对如何改变它以包含上述内容有点困惑.

My JS is pretty weak, so I'm a little confused on how to alter this to include the above.

<script type="text/javascript"> 
$(document).ready(function() {
    $("#order").sortable({
        update : function (event, ui) {
            order = $('#order').sortable('serialize');
            $.ajax({
                url: "<?=base_url().'admin/category/update_order'?>",
                type: "POST",
                data: order,
                success: function(response){
                    console.log(response);
                }
            });
        }
    });
}
);
</script>

推荐答案

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.

这篇关于如何将 Codeigniter 中的 CSRF 包含到 ajax 数据中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆