在$ .ajax中的beforeSend设置+在$ .ajax中的beforeSend [英] beforeSend in $.ajaxSetup + beforeSend in $.ajax

查看:677
本文介绍了在$ .ajax中的beforeSend设置+在$ .ajax中的beforeSend的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为解决CSRF问题,我为Ajax使用了客户端设置:

To solve the CSRF problem, I use a client-side setup for Ajax:

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        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;
        }
        if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
            // Only send the token to relative URLs i.e. locally.
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    }
});

直到今天,一切正常. 但是现在我需要在发布之前做一些检查:

Until today, everything worked fine. But now I need to do some check before post:

var check;
//...
$.ajax({
    //...
    beforeSend: function(xhr){
        if (check == 1){
            xhr.abort();
        }
    },
    success: function(data){
        //...
    }
});

CSRF验证失败.请求中止. 据我了解,我只是取消了针对新功能的ajaxSetup动作. 如何将这两件事结合起来?

Have CSRF verification failed. Request aborted. As I understand it, I just cancel the action of ajaxSetup for the new function. How to combine these two things?

推荐答案

使用$(document).ajaxSend(function(ev, jqhr, settings) { ... })代替.ajaxSetup.

正如您所说,.ajaxSetup定义了一个默认处理程序,然后可以将其覆盖.使用.ajaxSend,您可以注册多个处理程序以在发送ajax请求之前触发.与自定义beforeSend处理程序配合正常.

As you said .ajaxSetup defines a default handler which then can be overriden. With .ajaxSend you can register multiple handlers to fire before an ajax request is sent. Works fine with custom beforeSend handler.

这篇关于在$ .ajax中的beforeSend设置+在$ .ajax中的beforeSend的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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