view.py
def ajax(request): ???if request.method == ‘GET‘: ???????obj = AjaxForm() ???????return render(request,‘ajax.html‘,{‘obj‘:obj}) ???else: ???????ret = {‘status‘:‘no‘,‘message‘:None} ???????import json ???????obj=AjaxForm(request.POST) ???????if obj.is_valid(): # 这里开始做的数据验证 ???????????ret[‘status‘] = ‘yes‘ ???????????print(obj.cleaned_data) ???????????# 跳转,ajax方式提交不会直接跳转,需交给js处理 ???????????# return redirect(‘http://www.baidu.com‘) ???????????return HttpResponse(json.dumps(ret)) ???????else: ???????????print(obj.errors) ?# json.dumps里传python的基本数据类型,ErrorDict是继承dict的 ???????????print(type(obj.errors)) # <class ‘django.forms.utils.ErrorDict‘> ???????????ret[‘message‘] = obj.errors ???????????# 错误的信息显示在页面上 ???????????return HttpResponse(json.dumps(ret))
form类
html
<body><form id="fm" action="/ajax/" method="post" novalidate> ???{% csrf_token %} ???<p>{{ obj.username.label }}:{{ obj.username }}</p> ???<p>{{ obj.user_id.label }}:{{ obj.user_id }}</p> ???<input type="button" value="Ajax提交" id="btn"></form><script src="/static/js/jquery-3.3.1.js"></script>‘<script> ???$(function () { ???????$(‘#btn‘).click(function () { ???????????$.ajax({ ???????????????url:‘/ajax/‘, ???????????????type:‘POST‘, ???????????????data:$(‘#fm‘).serialize(), ???????????????dataType:‘JSON‘, ???????????????success:function (arg) { ???????????????????//arg:需包含状态信息,错误信息 ???????????????????if(arg.status == ‘yes‘){ // 跳转 ???????????????????????window.location.href="http://www.baidu.com" ???????????????????} ???????????????????console.log(arg) ???????????????} ???????????}) ???????}) ???})</script></body>
Django以ajax方式提交form
原文地址:https://www.cnblogs.com/zq8421/p/10439299.html