一、方法
is_ajax() 判断是否为ajax请求
二、Ajax GET示例
模板代码
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function ajax_get() {
$.get('/test_ajax/', function(data){
console.log(data)
})
}
</script>
</head>
<body>
<a href="#" onclick="ajax_get();">ajax_post</a>
</body>
</html>
视图
代码语言:javascript复制<span class="hljs-keyword">from</span> django.http.response <span class="hljs-keyword">import</span> JsonResponse
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_ajax</span><span class="hljs-params">(req)</span>:</span>
print(req.is_ajax())
<span class="hljs-keyword">return</span> JsonResponse({<span class="hljs-string">'code'</span>: <span class="hljs-number">200</span>})
路由地址
代码语言:javascript复制urlpatterns = [
path(<span class="hljs-string">r''</span>, main.index, name=<span class="hljs-string">'index'</span>),
path(<span class="hljs-string">r'test_ajax/'</span>, main.test_ajax, name=<span class="hljs-string">'test_ajax'</span>),
]
三、Ajax POST示例
模板代码
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
function ajax_post() {
$.post('/test_ajax/', function(data){
console.log(data)
})
}
</script>
</head>
<body>
<a href="#" onclick="ajax_post();">ajax_post</a>
</body>
</html>
ajaxSetup() 方法为将来的 AJAX 请求设置默认值。
视图函数
代码语言:javascript复制<span class="hljs-keyword">from</span> django.http.response <span class="hljs-keyword">import</span> JsonResponse
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_ajax</span><span class="hljs-params">(req)</span>:</span>
print(req.is_ajax())
<span class="hljs-keyword">return</span> JsonResponse({<span class="hljs-string">'code'</span>: <span class="hljs-number">200</span>})
路由地址
代码语言:javascript复制urlpatterns = [
path(<span class="hljs-string">r''</span>, main.index, name=<span class="hljs-string">'index'</span>),
path(<span class="hljs-string">r'test_ajax/'</span>, main.test_ajax, name=<span class="hljs-string">'test_ajax'</span>),
]