博客列表 >前端交互的表单验证知识及案例与FormData()简化Ajax请求——2019年7月17日23时23分

前端交互的表单验证知识及案例与FormData()简化Ajax请求——2019年7月17日23时23分

嘿哈的博客
嘿哈的博客原创
2019年07月19日 17:40:441399浏览

JSON

JSON.parse(): 将JSON格式字符串转为JS对象;

JSON.stringify(): 将JS对象转为JSON格式字符串;

不允许注释,支持数据类型:Number String Boolean Array Object Null

从前端发送JSON数据:注意要修改POST请求头

前端处理从服务器返回的JSON数据:request.setRequestHeader('content-type','application/json;charset=utf-8');

FormData() 演示:var data = new FormData(form表单name属性值);

简化Ajax请求,POST可以去掉请求头,用表单数据初始化FormData表单对象,会自动忽略disabled和按钮的表单数据

前端处理从服务器返回的JSON数据

JSON.parse.jpg

从前端发送JSON数据:

 JSON.stringify.jpg

前后端交互案例:


实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax-POST</title>
</head>
<body>
    <h2>用户登陆</h2>
    <form action="" name="login">
        <p>
            <label for="username" >用户名:</label>
            <input type="text" name="username" id="username">
        </p>
        <p>
            <label for="email" >邮箱:</label>
            <input type="text" name="email" id="email">
        </p>
        <p>
            <label for="password" >密码:</label>
            <input type="password" name="password" id="password">
        </p>
        <p>
            <label for="remember"></label>
            <select name="remember" id="remember">
                <option value="1">一天</option>
                <option value="7">七天</option>
            </select>
        </p>
        <p>
            <button type="button" name="submit">登陆</button>
        </p>
    </form>
    <script>
        //获取相关变量
        var login = document.forms.namedItem('login' );
        var btn = login.submit;
        var request = new XMLHttpRequest();
        //监听输入框内容
        login.username.addEventListener('blur', isEmpty, false);
        login.email.addEventListener('blur',isEmpty,false);
        login.password.addEventListener('blur',isEmpty,false);
        //事件方法
        function isEmpty(ev) {
            if (ev.target.value.length === 0 ) {
                if(ev.target.nextElementSibling ===null){
                    var tips = document.createElement('span');
                    switch (ev.target.name) {
                        case 'username':
                            tips.innerText = '用户名不能为空';
                            break;
                        case 'email':
                            tips.innerText = '邮箱不能为空';
                            break;
                        case 'password':
                            tips.innerText = '密码不能为空';
                            break;
                        default:
                            tips.innerText = '未知错误';
                     }
                    ev.target.parentNode.appendChild(tips);
                }
                ev.target.focus();

            }
        }
        //消除提示信息
        login.username.addEventListener('input', cleartips, false);
        login.email.addEventListener('input',cleartips,false);
        login.password.addEventListener('input',cleartips,false);
        function cleartips(ev) {
            var tips = ev.target.nextElementSibling;
            if (tips !== null){
                tips.parentNode.removeChild(tips);
            }
        }
        //Ajax异步验证
        btn.addEventListener('click',check,false);

        function check(ev) {
            var username = login.username.value;
            var email = login.email.value;
            var password = login.password.value;
            var remember = login.remember.value;

            if (username.length === 0 ||email.length === 0 || password.length=== 0 ){

                ev.target.removeEventListener('click',check,false);

                var blurEvent = new Event('blur');
                login.username.dispatchEvent(blurEvent);
                return false;
            }
            var obj = {
                username : username,
                email : email,
                password : password,
                remember :remember
            };

            var data = JSON.stringify(obj);
            console.log(data);
            request.addEventListener('readystatechange',successCallback,false);
            request.open('POST','php/check2.php',true);
            request.setRequestHeader('content-type','application/json;charset=utf-8');
            request.send(data);

        }
        function successCallback(ev) {
            if(request.readyState ===4){
                // console.log(request.responseText);
                var obj = JSON.parse(request.responseText);
                var tips = document.createElement('span');
                var url = '';

                switch (obj.status) {
                    case 1:
                        tips.innerText = obj.message + '正在跳转中';
                        url = 'php/admin.php';
                        break;
                    case 0:
                        tips.innerText = obj.message;
                        break;
                    default:
                        tips.innerText = '未知错误';
                        break;
                }
              btn.parentNode.appendChild(tips);
                setTimeout(function () {
                    location.href = url;
                },3000);

            }
        }
    </script>
</body>
</html>

运行实例 »

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

效果图:

1.JPG


FormData简化Ajax请求实例

360截图20190719173939077.jpg演示案例:


实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FormData序列化表单数据</title>
</head>
<body>
    <h2>用户登陆</h2>
    <form action="" name="login">
        <p>
            <label for="username" >用户名:</label>
            <input type="text" name="username" id="username">
        </p>
        <p>
            <label for="email" >邮箱:</label>
            <input type="text" name="email" id="email">
        </p>
        <p>
            <label for="password" >密码:</label>
            <input type="password" name="password" id="password">
        </p>
        <p>
            <label for="remember"></label>
            <select name="remember" id="remember">
                <option value="1">一天</option>
                <option value="7">七天</option>
            </select>
        </p>
        <p>
            <button type="button" name="submit">登陆</button>
        </p>
    </form>
    <script>
        //获取相关变量
        var login = document.forms.namedItem('login' );
        var btn = login.submit;
        var request = new XMLHttpRequest();
        //监听输入框内容
        login.username.addEventListener('blur', isEmpty, false);
        login.email.addEventListener('blur',isEmpty,false);
        login.password.addEventListener('blur',isEmpty,false);
        //事件方法
        function isEmpty(ev) {
            if (ev.target.value.length === 0 ) {
                if(ev.target.nextElementSibling ===null){
                    var tips = document.createElement('span');
                    switch (ev.target.name) {
                        case 'username':
                            tips.innerText = '用户名不能为空';
                            break;
                        case 'email':
                            tips.innerText = '邮箱不能为空';
                            break;
                        case 'password':
                            tips.innerText = '密码不能为空';
                            break;
                        default:
                            tips.innerText = '未知错误';
                     }
                    ev.target.parentNode.appendChild(tips);
                }
                ev.target.focus();

            }
        }
        //消除提示信息
        login.username.addEventListener('input', cleartips, false);
        login.email.addEventListener('input',cleartips,false);
        login.password.addEventListener('input',cleartips,false);
        function cleartips(ev) {
            var tips = ev.target.nextElementSibling;
            if (tips !== null){
                tips.parentNode.removeChild(tips);
            }
        }
        //Ajax异步验证
        btn.addEventListener('click',check,false);

        function check(ev) {
            var username = login.username.value;
            var email = login.email.value;
            var password = login.password.value;
            var remember = login.remember.value;

            if (username.length === 0 ||email.length === 0 || password.length=== 0 ){

                ev.target.removeEventListener('click',check,false);

                var blurEvent = new Event('blur');
                login.username.dispatchEvent(blurEvent);
                return false;
            }


            // var data = JSON.stringify(obj);
            // console.log(data);
            request.addEventListener('readystatechange',successCallback,false);
            request.open('POST','php/check1.php',true);

            request.send(new FormData(login));

        }
        function successCallback(ev) {
            if(request.readyState ===4){
                // console.log(request.responseText);
                var obj = JSON.parse(request.responseText);
                var tips = document.createElement('span');
                var url = '';

                switch (obj.status) {
                    case 1:
                        tips.innerText = obj.message + '正在跳转中';
                        url = 'php/admin.php';
                        break;
                    case 0:
                        tips.innerText = obj.message;
                        break;
                    default:
                        tips.innerText = '未知错误';
                        break;
                }
              btn.parentNode.appendChild(tips);
                setTimeout(function () {
                    location.href = url;
                },3000);

            }
        }
    </script>
</body>
</html>

运行实例 »

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

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议