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)
注意点:
HttpResponse(json.dumps(response_data),content_type=”application/json”)
JsonResponse(response_data)