直接上代码:
HTML,由Form插件自动生成input标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax提交Form验证</title>
</head>
<body>
<form action="/ajaxForm/" method="post" id="fm">
{% csrf_token %}
<p>username:{{ user.username }}<span id="username_span"></span></p>
<p>gender:{{ user.gender }}<span id="gender_span"></span></p>
<p><input type="button" value="Ajax提交" id="fm_submit"></p>
</form>
<script src="/static/jquery-3.3.1.min.js"></script>
<script>
$(function(){
$("#fm_submit").click(function(){
$.ajax({
url:"/ajaxForm/",
type:"post",
dataType:"JSON",
data:$("#fm").serialize(),
success:function(args){
if (args.status == "OK"){
window.location.href("Http://www.baidu.com")
}else if(args.status=="NG"){
console.log(args.msg)
$("#username_span").html(args.msg.username[0])
}
}
})
})
})
</script>
</body>
</html>
VIEWS代码
from django.shortcuts import render,redirect,HttpResponse
from django import forms
from django.forms import widgets
from app1 import models
import json
class AjaxForm(forms.Form):
username = forms.CharField(
required=True,
min_length=3,
error_messages={
"min_length":"用户名输入不正确",
}
)
gender = forms.BooleanField(
widget=widgets.RadioSelect(choices=[(0,"男"),(1,"女"),]),
required=False
)
# Create your views here.
def ajaxForm(request):
if request.method=="GET":
user = AjaxForm()
print("heheh ")
return render(request,"AjaxForm.html",{"user":user})
else:
ret = {"status": "NG", "msg": None}
af = AjaxForm(request.POST)
if af.is_valid():
print(af.cleaned_data)
models.User.objects.create(**af.cleaned_data)
ret["status"]="OK"
return HttpResponse(json.dumps(ret))
else:
print("NG")
ret["msg"] = af.errors
return HttpResponse(json.dumps(ret))
MODELS数据库表:
from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=50)
gender = models.BooleanField()
URL路由:
from django.contrib import admin
from django.urls import path
from app1 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('ajaxForm/', views.ajaxForm),
]