laravel ajax post请求携带csrf token

2020-03-27 17:59   Tags:

jquery 写法

        $.ajaxSetup({
            headers: {
                'X-XSRF-TOKEN': getCookie('XSRF-TOKEN')
            }
        });
        //下面执行post请求
        $.post()

封装一个取cookie函数

这个我经常使用,每次用到了就去w3school复制一下

    function getCookie(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

参考:

https://www.w3school.com.cn/js/js_cookies.asp

https://eyehere.net/2015/laravel-ajax-csrf/

https://blog.csdn.net/zhezhebie/article/details/78540343

发表评论

电子邮件地址不会被公开。 必填项已用*标注