Django 在 JQuery AJAX 请求中说 is_ajax 为假 [英] Django says is_ajax is false on a JQuery AJAX request

查看:22
本文介绍了Django 在 JQuery AJAX 请求中说 is_ajax 为假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文: chrome 浏览器扩展使用 JQuery 请求来自远程 django 应用程序的响应.Django 识别出请求是通过 AJAX 发出的,并以Hello AJAX!"作为响应.我的练习基于 这个很好的例子.因为这个请求是从 chrome 扩展发出的,所以请求是跨站点的,所以我在我的 Django 视图上使用了 @CSRF_exempt 装饰器.

Context: a chrome browser extension uses JQuery to request a response from a remote django app. Django recognizes that the request is made via AJAX and responds with "Hello AJAX!". I'm basing my exercise off this great example. Because this request is being made from a chrome extension, the request is being made cross site, so I've used the @CSRF_exempt decorator on my Django view.

问题:我的 Django 视图没有将请求识别为 AJAX 请求,而是响应 Hello AJAX! 而不是响应 Hello not AJAX!代码>.

Problem: My Django view is not recognizing the request as an AJAX request, and instead of responding Hello AJAX! it responds Hello not AJAX!.

我的 Django 视图:
(url /xhr_test 使用如下视图)

@csrf_exempt
def check_login_extension(request):
    if request.is_ajax():
        message = "Hello AJAX!"
    else:
        message = "Hello not AJAX"
    return HttpResponse(message)

我的 JQuery 请求:

function xhrconnect() {
    $.get("http://localhost:8000/xhr_test", function(data) {
      document.getElementById('xhrmsg').innerHTML = (data);
    });
}

推荐答案

通过 jQuery 源代码,它看起来像 $.ajax()(因此 $.get()$.post() 等)会自动将 crossDomain 选项设置为 true 如果它看到您正在制作跨域请求,你是(相关代码在这里).并且在实际的 AJAX 请求中,如果设置了 crossDomain(相关代码在此).

Going through the jQuery source, it looks like $.ajax() (and therefore $.get(), $.post(), etc) will automatically set the crossDomain option to true if it sees that you're making a cross-domain request, which you are (relevant code here). And in the actual AJAX request, jQuery won't set the HTTP_X_REQUESTED_WITH header that Django needs for is_ajax() if crossDomain is set (relevant code here).

我认为解决此问题的最简单方法是将 crossDomain 显式设置为 false:

I think the easiest way to fix this is to explicitly set crossDomain to false:

function xhrconnect() {
    $.ajax({
        url: "http://localhost:8000/xhr_test", 
        success: function(data) {
            document.getElementById('xhrmsg').innerHTML = (data);
        },
        crossDomain: false
    });
}

如果这不起作用,您可以尝试使用 AJAX 预过滤功能手动设置请求的 HTTP_X_REQUESTED_WITH 标头.

If that doesn't work, you could try using an AJAX prefilter function to manually set the HTTP_X_REQUESTED_WITH header on the request.

这篇关于Django 在 JQuery AJAX 请求中说 is_ajax 为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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