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

Django->Ajax 传输参数和接受参数方式

2017-08-17 11:33 525 查看
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: