首页 > 解决方案 > 即使 http 请求确实包含 XMLHttpRequest 参数,ajax 测试也会返回 false

问题描述

我有一个功能视图。我希望它测试收到的请求是否是 AJAX 请求,并根据此检查的结果做不同的事情。

功能真的不重要。我实际上已经用三行函数替换了它,只是为了检查请求是否是 AJAX,但结果仍然是错误的。

根据django网站,request.is_ajax():

Returns True if the request was made via an XMLHttpRequest, by checking the HTTP_X_REQUESTED_WITH header for the string 'XMLHttpRequest'. Most modern JavaScript libraries send this header. If you write your own XMLHttpRequest call (on the browser side), you’ll have to set this header manually if you want is_ajax() to work.

因此,在我的 javascript 代码中,我确保设置了标题(在创建并打开 XHTML 连接之后):

request.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');

最后,我启动tshark查看数据包的http头,果然,头字段在那里:

Hypertext Transfer Protocol
    GET /?&sort_options=most-comments HTTP/1.1\r\n
        .....
        Request Method: GET
        Request URI: /?&sort_options=most-comments
            Request URI Path: /
            Request URI Query: &sort_options=most-comments
                Request URI Query Parameter: sort_options=most-comments
       .......
    **HTTP_X_REQUESTED_WITH: XMLHttpRequest\r\n**  
       ......

所以它显然在那里。在我看来,我把所有东西都删掉了,此时我所做的就是:

def ajax_view(request):
      if request.is_ajax():
      render(request, 'test.html')

但它 is_ajax 返回 false。我不明白。

标签: javascriptdjangoajax

解决方案


令人难以置信的是,在挠了挠头,挖了 2 个小时却没有让它工作之后,在发布这个问题后,我立即偶然发现了另一个提供解决方案的答案

'X-Requested-With': 'XMLHttpRequest'

X-REQUESTED-WITH,而不是 Django 网站所说的 HTTP_X_REQUESTED_WITH 。


推荐阅读