裝飾器和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>