您的位置:首页 > 编程语言 > Go语言

关于Django 使用$.post(),$.get(),$.ajax()等异步操作时的一些问题的解决方案

2018-01-29 14:52 766 查看
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/,可以看到如下的效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐