gpt4 book ai didi

javascript - Django Ajax 通信,Django 不识别为 Ajax(使用 request.is_ajax() )

转载 作者:行者123 更新时间:2023-12-03 01:27:23 25 4
gpt4 key购买 nike

我正在将 Ajax 与 Django 结合使用。数据被进一步传输,但不被识别为 Ajax。浏览器 Chrome/Firefox;

为了检查请求是否通过ajax完成,我使用:

`request.is_ajax()` method, but this fails, not true, so I checked this method how is working and:

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

我验证了 META.get('HTTP_X_REQUESTED_WITH') 并得到 None;

我认为是 ContentType 的问题,或者我需要设置另一个 header 。但如何?我的 JavaScript 是这样设置的:

xhr.open('post', event.target.action, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest");
xhr.send(data));

进一步检查似乎 request.Meta 也不包含 Content-type。

最佳答案

来自官方documentation :

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

所以 header 的名称应该是X-Requested-With:

xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

关于javascript - Django Ajax 通信,Django 不识别为 Ajax(使用 request.is_ajax() ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51466018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com