ajax前端验证及发送数据

2020-05-28  本文已影响0人  靠还是你

引入所需要的插件

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="https://www.layuicdn.com/layui/css/layui.css" />
<script src="https://www.layuicdn.com/layui/layui.js"></script>

ajax代码逻辑部分

$(function(){
        $('#Submit').on('click',function(){
            var username = $('input[name=username]');
            var password = $('input[name=password]');

            if(username.val() == ''){
                layer.msg('用户名不能为空!', {time: 1500, icon: 2});
                username.focus();
                return false;
            }

            if(password.val() == ''){
                layer.msg('密码不能为空!', {time: 1500, icon: 2});
                password.focus();
                return false;
            }

            $.ajax({
                // async:false,
                url : "youUrl",
                data: $('#theFormId').serialize(), //<from id="theFormId"> 定义form表单id
                type:'post',
                dataType:'json',
                success:function(res){
                    //根据res 返回的数据进行逻辑判断
                    if (1 == res.code) {
                        if (5 == res.data.status) {
                            layer.alert(res.msg, {icon: 2},function(){
                                window.location.href = res.url;
                            });
                        }else{
                            window.location.href = res.url;

                    } else {
                        layer.closeAll();
                        if ('vertify' == res.data.status) {
                            fleshVerify();
                        }
                        
                        if (2 == res.data.status) {
                            layer.alert(res.msg, {icon: 4});
                        } else {
                            layer.msg(res.msg, {icon: 2,time: 1500});
                        }
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown) {
                    layer.closeAll();
                    layer.alert('网络失败,请刷新页面后重试', {icon: 5});
                }
            });
        });
    });
上一篇 下一篇

猜你喜欢

热点阅读