演示jQuery操作ajax技术POST方法实现异步请求
代码
分布式路由层(简写)
urlpatterns = [
url(r'^test_post$',views.test_post),
url(r'^test_post_server$',views.test_post_server),
]
templates层:test_post.html(简写)
<body>
<script src="/static/js/jquery-1.11.3.js"></script>
{% csrf_token %}
<p>
用户名:<input type="text" id="username">
</p>
<script>
$(function(){
$('#btn').click(function(){
var params = {
username: $('#username').val(),
csrfmiddlewaretoken: $("[name=csrfmiddlewaretoken]").val()
}
//jQuery操作ajax的POST方法:$.post(url,data,function(data){},type)
$.post('/ajax/test_post_server',params,function(res){
alert(res.msg)
},'json');
});
})
</script>
views层
def test_post(request):
return render(request,'test_post.html')
def test_post_server(request):
username = request.POST.get('username')
#制作要返回的json串
msg = 'name is %s'%(username)
d = {'msg':msg}
#django的方法返回json串给前端
return JsonResponse(d)
效果
前端用户名框中输入用户名,按提交按钮后弹框:name is xxx,实现异步效果