将AJAX请求的标头设置为Django

时间:2015-04-28 23:04:27

标签: python ajax django

我想测试一些AJAX请求到我的Django站点,但服务器认为我的测试工具的请求不是AJAX请求。我需要设置什么HTTP标头?

服务器代码有这样的测试:

# in myapp/ajax.py
def my_request(request, some_id):
    if request.is_ajax():
        return json.dumps([some_id, 'processed for AJAX'])

    # some other processing, or an error

我正在使用Postman发送我的AJAX请求,并且我已经学会将Accept标头设置为application/json,但是我设置了哪个标头来表明它是一个AJAX请求?

在Django代码中,我找到了测试方法:

def is_ajax(self):
    return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

当我将HTTP_X_REQUESTED_WITH标头设置为XMLHttpRequest时,测试仍然失败。

2 个答案:

答案 0 :(得分:5)

当我打开Chrome开发者工具时,我发现常规的AJAX请求包含设置为X-Requested-With的标头XMLHttpRequest。在Postman请求中添加该标头使其工作。这只是一个略有不同的名字。

如果您要制作修改数据的AJAX请求,则需要切换到发出POST请求。这使Django的cross-site request forgery工具发挥作用,因此您需要从其他形式的隐藏字段中复制CSRF令牌,然后在测试AJAX请求时将其粘贴到X-CSRFToken标头中。

答案 1 :(得分:0)

无论何时我通过Django发送Ajax数据,我总是把它放在顶部。

// django ajax request info
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 csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
        // or any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
            // Send the token to same-origin, relative URLs only.
            // Send the token only if the method warrants CSRF protection
            // Using the CSRFToken value acquired earlier
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});