Django> = 3.1和is_ajax [英] Django >= 3.1 and is_ajax
问题描述
HttpRequest.is_ajax()
.
如果要从浏览器请求页面,我想返回html,如果从javascript或以编程方式调用,则要返回 JsonResponse
.
I want to return html if the page is requested from a browser and as JsonResponse
if called from javascript or programmatically.
我正在寻求有关操作方法的指导.
I am seeking guidance on how to do that.
https://docs.djangoproject.com/zh-CN/3.1/ref/request-response/#django.http.HttpRequest.is_ajax
推荐答案
检查 HTTP_X_REQUESTED_WITH
标头
def sample_view(request):
is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
从 3.1版发行说明
不建议使用
HttpRequest.is_ajax()
方法,因为该方法依赖于jQuery表示AJAX调用的特定方式,而当前用法倾向于使用JavaScript Fetch API.根据您的用例,您可以编写自己的AJAX检测方法,或者如果您的代码取决于客户端的接受HTTP标头,则可以使用新的HttpRequest.accepts()
方法.
The
HttpRequest.is_ajax()
method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method, or use the newHttpRequest.accepts()
method if your code depends on the client Accept HTTP header.
这篇关于Django> = 3.1和is_ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!