Django表示,jQuery AJAX请求中的is_ajax是false [英] Django says is_ajax is false on a JQuery AJAX request

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

问题描述

上下文:Chrome浏览器扩展使用JQuery从远程django应用程序请求响应。 Django认识到请求是通过AJAX进行的,并以Hello AJAX!作为响应。我基于我的运动这个很好的例子。因为这个请求是由chrome扩展名进行的,所以请求是跨站点的,所以我在Django视图中使用了 @CSRF_exempt decorator。

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! 它响应你好不是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请求中,jQuery将不会设置Django需要的 is_ajax() HTTP_X_REQUESTED_WITH code> 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是false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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