1. 程式人生 > >Form組件驗證之ajax提交數據並顯示錯誤信息

Form組件驗證之ajax提交數據並顯示錯誤信息

bmi serial ret else sna 1-43 rect aid serialize

前端登陸界面(重點是js操作--接收到後臺發來的錯誤信息怎麽在頁面顯示出來)

技術分享圖片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>用戶登錄</h1>
    <form id="f1" action="/login/" method="POST">
        {% csrf_token %}
        
<p> <input type="text" name="user" />{{ obj.errors.user.0 }} </p> <p> <input type="password" name="pwd" />{{ obj.errors.pwd.0 }} </p> <input type="submit" value="提交" /> <a onclick="submitForm();">提交</a> </form> <script src="
/static/jquery-1.12.4.js"></script> <script> function submitForm(){ $(.c1).remove(); $.ajax({ url: /ajax_login/, type: POST, data: $(#f1).serialize(),// user=alex&pwd=456&csrftoen=dfdf dataType:
"JSON", success:function(arg){ console.log(arg); if(arg.status){ }else{ $.each(arg.msg,function(index,value){ console.log(index,value); var tag = document.createElement(span); tag.innerHTML = value[0]; tag.className = c1; $(#f1).find(input[name="+ index +"]).after(tag); }) } } }) } </script> </body> </html>
View Code

views.py中接收數據並作驗證,然後把錯誤信息返回給前端

技術分享圖片
from django.shortcuts import render,redirect,HttpResponse
from django.forms import Form
from django.forms import fields
from django.forms import widgets

class LoginForm(Form):
    user = fields.CharField(required=True)
    pwd = fields.CharField(min_length=18)


def login(request):
    if request.method == GET:
        return render(request,login.html)
    else:
        obj = LoginForm(request.POST)
        if obj.is_valid():
            print(obj.cleaned_data)
            return redirect(http://www.baidu.com)
        return render(request,login.html,{obj: obj})


ajax接收並發送數據
def ajax_login(request): 
    import json
    ret = {status: True,msg: None}
    obj = LoginForm(request.POST)
    if obj.is_valid():
        print(obj.cleaned_data)
    else:
        # print(obj.errors) # obj.errors對象
        ret[status] = False
        ret[msg] = obj.errors
    v = json.dumps(ret)
    return HttpResponse(v)

#
# class TestForm(Form):
#     t1 = fields.CharField(
#         required=True,
#         max_length=8,
#         min_length=2,
#         error_messages={
#             ‘required‘: ‘不能為空‘,
#             ‘max_length‘: ‘太長‘,
#             ‘min_length‘: ‘太短‘,
#         }
#     )
#     t2 = fields.IntegerField(
#         min_value=10,
#         max_value=1000,
#         error_messages={
#             ‘required‘: ‘t2不能為空‘,
#             ‘invalid‘: ‘t2格式錯誤,必須是數字‘,
#             ‘min_value‘: ‘必須大於10‘,
#             ‘max_value‘: ‘必須小於1000‘,
#         },
#     )
#     t3 = fields.EmailField(
#         error_messages={
#             ‘required‘: ‘t3不能為空‘,
#             ‘invalid‘: ‘t3格式錯誤,必須是郵箱格式‘,
#         }
#     )





class TestForm(Form):
    t1 = fields.CharField(required=True,max_length=8,min_length=2,
        error_messages={
            required: 不能為空,
            max_length: 太長,
            min_length: 太短,
        }
    )
    t2 = fields.EmailField()

def test(request):
    if request.method == "GET":
        obj = TestForm()
        return render(request,test.html,{obj: obj})
    else:
        obj = TestForm(request.POST)
        if obj.is_valid():
            print(obj.cleaned_data)
        else:
            print(obj.errors)
        return render(request,test.html,{obj:obj})



class RegiterForm(Form):
    user = fields.CharField(min_length=8)
    email = fields.EmailField()
    password = fields.CharField()
    phone = fields.RegexField(139\d+)


def register(request):
    if request.method == GET:
        obj = RegiterForm()
        return render(request,register.html,{obj:obj})
    else:
        obj = RegiterForm(request.POST)
        if obj.is_valid():
            print(obj.cleaned_data)
        else:
            print(obj.errors)
        return render(request,register.html,{obj:obj})
View Code

Form組件驗證之ajax提交數據並顯示錯誤信息