Django--ajax(高级版本)
2019-01-07 本文已影响0人
一纸繁鸢w
使用json+jquery
1. $.ajax()
$.ajax({
type:"POST",
url:"{% url 'ajaxapp:test' %}",
data:"name=Mr_lee&age=18&csrfmiddlewaretoken="+"{{ csrf_token }}",
success:function (msg) {
alert(msg)
}
})
2. views
def query1(request):
def user_default(u):
if isinstance(u,User):
return {'id':u.id,'name':u.name,'age':u.age,'salary':u.salary}
user = User.objects.get(pk=1)
return JsonResponse(user,safe=False,json_dumps_params={"default":user_default})
其他两种形式
$.get(
"{% url "ajaxapp:test" %}",
"name=Mr_lee&age=18",
function(data){
alert(data)
},
"json"
)
$.post(
"{% url "ajaxapp:test" %}",
"name=Mr_lee&age=18&csrfmiddlewaretoken="+"{{ csrf_token }}",
function(data){
alert(data)
},
"text"
)