装饰器和ajax和json格式:
在后台:
import json
def auth_ajax(func):
def inner(request, *args, **kwargs):
request.data = request.POST
# path = request.path #跳转的路径
# get_data = request.get_full_path()
print(request.body)
try:
request.data = json.loads(request.body.decode('utf-8')) #把数据转成字典格式
except Exception as e: # 捕捉异常,把异常信息打印出来
print(e)
res = func(request, *args, **kwargs)
return res
return inner
@auth_ajax
def index(request):
if request.method == 'GET':
return render(request, 'index.html')
elif request.method == 'POST':
# print(request.GET.get('name'))
# print(request.POST.get('name'))
print(request.data)
print(request.data.get('name'))
return HttpResponse('ok')
在前台:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/static/jquery-3.3.1.js"></script>
<title>Title</title>
</head>
<body>
<button id="btn">点我</button>
</body>
<script>
$("#btn").click(function () {
var dic = {'name': 'egon'} #定义一个字典信息
var da=JSON.stringify(dic) #把字典转为json字符串格式
$.ajax({
url: '/index/?name=lqz', #传给后端的地址,?后面的东西是为了证明后面的信息是从GET里面取
type: 'post', #请求的方式
contentType: 'application/json', #指定json格式
data:da, #传给后端的数据
success: function (data) {
console.log(data)
}
})
})
</script>
</html>