django版本:2.0.1
在Django中,如果要响应异步请求,需要用到is_ajax()方法进行判断:
实例:
前端代码:
<!--test.html-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<!--此处引用的菜鸟教程的jquery的静态文件-->
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
url = "example"; //异步请求的url地址
$.post(url, '', success, "json");
//异步请求的回调函数
function success(data) {
alert(data.answer);
}
})
</script>
</body>
</html>
后台代码:
# views.py
# -*- coding:utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
import json
def index(request):
return render(request, 'test.html')
def test(request):
if request.is_ajax():
data = {"answer": "answer"}
# json.dumps() 将数据转换成json对象
#ensure_ascii=False用于处理中文
return HttpResponse(json.dumps(data, ensure_ascii=False))
# urls.py
from django.urls import path
from myapp import views # 导入views模块
urlpatterns = [
path('', views.index),
path('example', views.test)
]
启动服务器,在浏览器中输入http://localhost:8000/,可以看到如下的效果