1.GET 方式
$.ajax({
url:'/hello/getTest',
type:'GET',
data:{'a':3333,'b':444},
success:function(data){
alert(data.message);
}
})
views->参数解析和用数据字典的方式返回json 数据(跨域名请求数据,则使用 jsonp字符串)
```
def getTest(request):
data = request.GET
print(data)
a = data.get('a')
b = data.get('b')
response_data = {}
response_data['result'] = 's'
response_data['message'] = a+b
return HttpResponse(json.dumps(response_data), content_type="application/json")
```
2.Post 方式
function postTest() {
$.ajax({
url:'/hello/postTest',
type:'POST',
data:{'a':3333,'b':444},
success:function(data){
alert(data.message);
}
})
}
views-> 引入from django.views.decorators.csrf import csrf_exempt,并且增加注解@csrf_exempt,目的是避开CSRF检查
@csrf_exempt
def postTest(request):
data = request.POST
print(data)
a = data.get('a')
b = data.get('b')
response_data = {}
response_data['result'] = 's'
response_data['message'] = a+b
return JsonResponse(response_data)
注意点:
- post 方式有避开CSRF检查,具体不回避CSRF检查的方式需要再研究
- 返回Json的方式有两种
HttpResponse(json.dumps(response_data),content_type=”application/json”)
JsonResponse(response_data)
本文介绍了Django中使用Ajax进行GET和POST请求的方式。对于GET请求,视图函数通过解析参数并以JSON响应。POST请求需使用@csrf_exempt注解以绕过CSRF检查。返回JSON数据可以使用HttpResponse或JsonResponse。对于POST不回避CSRF检查的处理方法,需要进一步探讨。
160

被折叠的 条评论
为什么被折叠?



