首页 新闻 会员 周边 捐助

使用 ajax 发送带有 csrftoken 的请求失败

0
悬赏园豆:20 [已关闭问题] 关闭于 2020-04-15 10:22

ajax 代码

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var xfzajax = {
    'get': function (args) {
        args['method'] = 'get';
        this.ajax(args);
    },
    'post': function (args) {
        args['method'] = 'post';
        this._ajaxSetup();
        this.ajax(args);
    },
    'ajax': function (args) {
        $.ajax(args);
    },
    '_ajaxSetup': function () {
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                }
            }
        });
    }
};

html 代码

<div class="form-group">
                            <div class="input-group">
                                <input type="text" class="form-control" name="telephone" placeholder="请输入手机号码">
                            </div>
                            <div class="input-group">
                                <input type="text" class="form-control" name="password" placeholder="请输入密码">
                            </div>
                            <div class="input-group">
                                <label class="remember-label">
                                    <input type="checkbox" name="remember" value="1">
                                    记住我
                                </label>
                            </div>
                            <div class="input-group">
                                <input type="submit" class="submit-btn" value="立即登录">
                            </div>
                        </div>

发送 post 请求的代码

xfzajax.post({
            'url': '/xfzauth/login/',
            'data': {
                'telephone': telephone,
                'password': password,
                'remember': remember ? 1 : 0
            },
            'success': function(result) {
                console.log(result);
            },
            'fail': function(error) {
                console.log(error);
            }
        });

错误提示

请求头信息

飞翔的石牌人的主页 飞翔的石牌人 | 初学一级 | 园豆:37
提问于:2020-04-15 10:21
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册