Blogger Information
Blog 63
fans 1
comment 0
visits 76066
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用Ajax验证表单数据(使用JSON)
桃儿的博客
Original
810 people have browsed it

使用Ajax验证表单数据(使用JSON)

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> 使用Ajax验证表单数据</title>
</head>
<body>
<form name="login" method="post" onsubmit="return false">
    <p>
        <label for="email">邮箱:</label>
        <input type="email" id="email" name="email" placeholder="example@gmail.com">
        <span style="color: red" id="error_email">*</span>
    </p>
    <p>
        <label for="password">密码:</label>
        <input type="password" id="password" name="password" placeholder="不少于6位">
        <span style="color: red" id="error_psw">*</span>
    </p>
    <p>
        <button id="submit" type="button">提交</button>
        <span id="result"></span>
    </p>
</form>


<script>
    // 获取必要的元素,以及提示信息的占位符元素
    var login=document.forms.namedItem('login');
    var submit=document.getElementById('submit');
    var error_email=document.getElementById('error_email');
    var error_psw=document.getElementById('error_psw');
    var result=document.getElementById('result');
    // 为提交按钮设置点击事件, 并分配一个事件响应函数(只需要名称即可)
    submit.addEventListener('click',checkUser,false);
    // 主函数: 定义提交事件函数, 内部会调用二个子函数,完成主要功能
    function checkUser() {
        //1.数据非空验证
        var user=isEmpty(login,error_email,error_psw);
        //2.Ajax异步验证
        return user ? verfiy(user,result):false;
    }
    //非空验证函数
    function isEmpty(form,error1,error2) {
        //获取表单控件中的内容,并清空前后空格
        var email=form.email.value.trim();
        var password=form.password.value.trim();
        // 先验证邮箱,再验证密码,并正确的设置焦点与返回值
        if(email.length===0){
            error1.innerText='邮箱不能为空';
            login.email.focus();
            return false;
        }else if(password.length===0){
            error2.innerText='密码不能为空';
            login.password.focus();
            return false;
        }
        // 非空验证通过, 则返回邮箱与密码组成的对象字面量,方便后续代码调用
        return {
            email:email,
            password:password
        }
    }
    //ajax
    function verfiy(user, result) {
        //1.创建request对象
        var request = new XMLHttpRequest();
        //2.监听响应状态
        request.onreadystatechange = function(){
            if (request.readyState === 4) { // 准备就绪
                if(request.status===200){
                    // console.log(request.responseText);
                    // 设置验证提示
                    // result.innerHTML = request.responseText;
                    //设置验证提示,JSON.parse()获取服务器信息
                    var obj=JSON.parse(request.responseText);
                    // console.log(obj);
                    switch(obj.status){
                        case 1:
                            result.style.color='red';
                            result.innerHTML=obj.message;
                            break;
                        case 2:
                            result.style.color='red';
                            result.innerHTML=obj.message;
                            break;
                        case 3:
                            result.style.color='green';
                            result.innerHTML=obj.message;
                            break;
                    }
                }
            }

            return false;
        };

        //3.设置请求参数
        request.open('post','admin/check.php',true);

        //4. 设置头信息,将内容类型设置为表单提交方式(固定模板语法结构)
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        //4.发送请求
        // 准备要提交的数据
        var data = 'email=' + user.email + '&password=' + user.password;
        //发送请求
        request.send(data);
    }
    // 添加input事件: 当用户修改错误数据时, 提示信息应该消失
    login.email.addEventListener('input',function () {
        error_email.innerText='';
        result.innerText='';
    },false);
    login.password.addEventListener('input',function () {
        error_psw.innerText='';
        result.innerText='';
    },false);
</script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


实例

<?php

//print_r($_POST);

$email = $_POST['email'];
$password = $_POST['password'];

$emailList = ['admin@php.cn', 'admin@html.cn', 'admin@py.cn'];
$pwd = md5('123456');

if (!in_array($email, $emailList)) {
//    echo '<span style="color: red">邮箱不正确</span>';

    // 从服务器返回json格式的数据,其实就是一个字符串,默认必须是UTF8编码
    // json_encode: 将php数组或数组转为json格式字符串
    echo json_encode(['status'=>1, 'message'=>'邮箱不正确']);



} else if (md5($password) !== $pwd) {
//    echo '<span style="color: red">密码不正确</span>';
    echo json_encode(['status'=>2, 'message'=>'密码不正确']);
} else {
//    echo '<span style="color: green">验证通过,正在跳转...</span>';
    echo json_encode(['status'=>3, 'message'=>'验证通过正在跳转']);

}

运行实例 »

点击 "运行实例" 按钮查看在线实例


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post