Form组件验证之ajax提交数据并显示错误信息

Posted 生如夏花和秋叶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Form组件验证之ajax提交数据并显示错误信息相关的知识,希望对你有一定的参考价值。

前端登陆界面(重点是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提交数据并显示错误信息的主要内容,如果未能解决你的问题,请参考以下文章

Django之form组件

Django之Form组件

Django之Form组件

Django之Form组件

Django框架基础之Form组件

Django 框架之Form组件