• 知问前端——Ajax提交表单


       本文,运用两大表单插件,完成数据表新增的工作。

       一、创建数据库

       创建一个数据库,名称为:zhiwen,表——user表,字段依次为:id、name、pass、email、sex、birthday、date。

       本人是使用的Navicat for MySQL创建的user表, user表的结构如下:

      

       所需的PHP文件:config.php、add.php。(本人没学过php,所以不过多解释)

       config.php:

    <?php
        header('Content-Type:text/html; charset=utf-8'); //防止乱码
        
        define('DB_HOST', 'localhost');
        define('DB_USER', 'root');
        define('DB_PWD', 'yezi');
        define('DB_NAME', 'zhiwen');
        
        $conn = @mysql_connect(DB_HOST, DB_USER, DB_PWD) or die('数据库链接失败:'.mysql_error());
        
        @mysql_select_db(DB_NAME) or die('数据库错误:'.mysql_error());
        
        @mysql_query('SET NAMES UTF8') or die('字符集错误:'.mysql_error());
    ?>

       add.php:

    <?php
        sleep(3); //睡眠3秒,以供测试
        require 'config.php';
        
        $query = "INSERT INTO user (name, pass, email, sex, birthday, date)
                  VALUES ('{$_POST['user']}', sha1('{$_POST['pass']}'), '{$_POST['email']}', '{$_POST['sex']}', '{$_POST['birthday']}', NOW())";
        
        mysql_query($query) or die('新增失败!'.mysql_error());
        
        echo mysql_affected_rows(); //正确插入返回1,报错返回错误信息
        
        mysql_close();
    ?>

       二、Loading制作

       在提交表单的时候,用于网络速度问题,可能会出现不同时间延迟。所以,为了更好的用户体验,在提交等待过程中,设置loading是非常有必要的。

       index.html:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>知问前端</title>
        <script type="text/javascript" src="jquery-1.12.3.js"></script>
        <script type="text/javascript" src="jquery-ui.js"></script>
        <script type="text/javascript" src="jquery.validate.js"></script>
        <script type="text/javascript" src="jquery.form.js"></script>
        <script type="text/javascript" src="index.js"></script>
        <link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico" />
        <link rel="stylesheet" type="text/css" href="jquery-ui.css" />
        <link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
        <div id="header">
            <div class="header_main">
                <h1>知问</h1>
                <div class="header_search">
                    <input type="text" name="search" class="search" />
                </div>
                <div class="header_button">
                    <button id="search_button">查询</button>
                </div>
                <div class="header_member">
                    <a href="###" id="reg_a">注册</a> | <a href="###" id="login_a">登录</a>
                </div>
            </div>
        </div>
        
        <form id="reg" action="123.html" title="会员注册">
            <ol class="reg_error"></ol>
            <p>
                <label for="user">账号:</label>
                <input type="text" name="user" class="text" id="user"></input>
                <span class="star">*</span>
            </p>
            <p>
                <label for="pass">密码:</label>
                <input type="password" name="pass" class="text" id="pass"></input>
                <span class="star">*</span>
            </p>
            <p>
                <label for="email">邮箱:</label>
                <input type="text" name="email" class="text" id="email"></input>
                <span class="star">*</span>
            </p>
            <p>
                <label>性别:</label>
                <input type="radio" name="sex" id="male" value="male" checked="checked"><label for="male"></label></input>
                <input type="radio" name="sex" id="female" value="female"><label for="female"></label></input>
            </p>
            <p>
                <label for="date">生日:</label>
                <input type="text" name="birthday" readonly="readonly" class="text" id="date"></input>
            </p>
        </form>
        <div id="loading">数据交互中...</div>
    </body>
    </html>
    View Code

       采用对话框式:

    $("#loading").dialog({
        autoOpen:false,
        modal:true,
        closeOnEscape:false, //按下Esc无效
        resizable:false,
        draggable:false,
        180,
        //height:80
        height:50  //height为何从80变为50,后面会讲解到
    }).parent().find(".ui-widget-header").hide(); //去掉header头

       css增加部分:

    #loading {
        background: url(img/loading.gif) no-repeat 20px center;
        line-height: 25px;
        font-size: 14px;
        font-weight: bold;
        text-indent: 40px; /* 首行缩进40像素  */
        color: #666;
    }

       所以style.css为:

    body {
        margin: 40px 0 0 0;
        padding: 0;
        font-size: 12px;
        font-family: 宋体;
        background: #fff;
    }
    /* 更改jQuery UI主题的对话框header的背景 */
    .ui-widget-header {
        background: url(img/ui_header_bg.png);
    }
    /* 按钮正常状态的背景 */
    .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default {
        background:url(img/ui_header_bg.png);
    }
    /* 按钮点击状态的背景 */
    .ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active {
        background:url(img/ui_white.png);
    }
    /* 工具提示的文本颜色 */
    .ui-tooltip {
        color: #666;
    }
    /* 邮箱自动补全的悬停背景色 */
    .ui-menu .ui-state-focus {
        background:url(img/ui_header_bg.png);
    }
    .ui-menu {
        color: #666;
    }
    /* 日历UI的今天单元格样式 */
    .ui-datepicker-today .ui-state-highlight {
        border:1px solid #eee;
        color:#f60;
    }
    /* 日历UI的选定单元格样式 */
    .ui-datepicker-current-day .ui-state-active {
        border:1px solid #eee;
        color:#06f;
    }
    .a {
        font-size: 30px;
    }
    #header {
        width: 100%;
        height: 40px;
        background: url(img/header_bg.png);
        position: absolute;
        top:0;
    }
    #header .header_main {
        width: 800px;
        height: 40px;
        margin: 0 auto;
    }
    #header .header_main h1 {
        font-size: 20px;
        margin: 0;
        padding: 0;
        color: #666;
        line-height: 40px;
        float: left;
        padding: 0 10px;
    }
    #header .header_search {
        padding: 6px 0 0 0;
        float: left;
    }
    #header .header_search .search {
        width: 300px;
        height: 24px;
        border: 1px solid #ccc;
        background: #fff;
        color: #666;
        font-size: 14px;
        text-indent: 5px;
    }
    #header .header_button {
        padding: 5px;
        float: left;
    }
    #header .header_member {
        float: right;
        line-height: 40px;
        color: #555;
        font-size: 14px;
    }
    #header .header_member a {
        text-decoration: none;
        font-size: 14px;
        color: #555;
    }
    #reg {
        padding: 15px 0 0 15px;
    }
    #reg p {
        margin: 10px 0;
        padding: 0;
    }
    #reg p label {
        font-size: 14px;
        color: #666;
    }
    #reg .star {
        font-size: 14px;
        color: maroon;  /* 红色太耀眼,换成棕色 */
    }
    #reg .succ {
        display: inline-block; /* 将<span>元素(内联)转变成内联块,而且<span>里还要有数据,插入的图片才能显示出来 */
        width: 28px;
        background: url(img/reg_succ.png) no-repeat;
    }
    #reg ol {
        margin:0;
        padding: 0 0 0 20px;
        color: maroon;
    }
    #reg ol li {
        height: 20px;
    }
    #reg .text {
        border-radius: 4px;
        border: 1px solid #ccc;
        background: #fff;
        width: 200px;
        height: 25px;
        line-height: 25px;
        text-indent: 5px;
        font-size: 13px;
        color: #666;
    }
    
    #loading {
        background: url(img/loading.gif) no-repeat 20px center;
        line-height: 25px;
        font-size: 14px;
        font-weight: bold;
        text-indent: 40px; /* 首行缩进40像素  */
        color: #666;
    }
    View Code

       三、Ajax提交

       最后,我们需要采用jquery.form.js插件对数据进行提交,而且在其他部分也需要做一些修改。

    //输入验证成功之后,进行提交
    submitHandler:function(form) {
        //alert("验证成功,准备提交中!");
        $(form).ajaxSubmit({
            url:"add.php",
            type:"post",
            beforeSubmit:function(formData,jqForm,options) {
                //提交之前,将“数据正在交互中...”对话框打开
                //打开之后,高度又默认增加了30,所以在初始化dialog时,height应-30,变为50
                $("#loading").dialog("open");
    
                //alert($("#reg").dialog("widget").html());
                //alert($("#reg").dialog("widget").find("button").eq(0).html()); //<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">Close</span>
                //alert($("#reg").dialog("widget").find("button").eq(1).html()); //<span class="ui-button-text">提交</span>
                $("#reg").dialog("widget").find("button").eq(1).button("disable"); //禁用提交按钮
            },
            success:function(responseText,statusText) {
                //alert(responseText); //新增成功,返回1
                if(responseText) {
                    $("#reg").dialog("widget").find("button").eq(1).button("enable");
                    $("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");
    
                    setTimeout(function() { //一秒之后执行该function代码
                        $("#loading").dialog("close");
                        $("#reg").dialog("close");
                        $("#reg").resetForm(); //重置表单
                        $("#reg span.star").html("*").removeClass("succ");
                        $("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");
                    }, 1000);
                }
            }
        });
    }

       故,index.js为:

    $(function() {
        $("#search_button").button({
            icons:{
                primary:"ui-icon-search",
            },
        });
    
        $("#loading").dialog({
            autoOpen:false,
            modal:true,
            closeOnEscape:false, //按下Esc无效
            resizable:false,
            draggable:false,
            180,
            //height:80
            height:50  //height为何从80变为50,后面会讲解到
        }).parent().find(".ui-widget-header").hide(); //去掉header头
    
        $("#reg_a").click(function() {
            $("#reg").dialog("open");
        });
    
        //$("#reg").dailog(...)返回的是jQuery对象,即对话框内容的div(id="reg")对象,所以可以连缀使用
        $("#reg").dialog({
            autoOpen:false,
            modal:true,
            resizable:false,
            320,
            height:340,
            buttons:{
                '提交':function() {
                    $(this).submit();
                }
            }
        }).buttonset().validate({
            //输入验证成功之后,进行提交
            submitHandler:function(form) {
                //alert("验证成功,准备提交中!");
                $(form).ajaxSubmit({
                    url:"add.php",
                    type:"post",
                    beforeSubmit:function(formData,jqForm,options) {
                        //提交之前,将“数据正在交互中...”对话框打开
                        //打开之后,高度又默认增加了30,所以在初始化dialog时,height应-30,变为50
                        $("#loading").dialog("open");
    
                        //alert($("#reg").dialog("widget").html());
                        //alert($("#reg").dialog("widget").find("button").eq(0).html()); //<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">Close</span>
                        //alert($("#reg").dialog("widget").find("button").eq(1).html()); //<span class="ui-button-text">提交</span>
                        $("#reg").dialog("widget").find("button").eq(1).button("disable"); //禁用提交按钮
                    },
                    success:function(responseText,statusText) {
                        //alert(responseText); //新增成功,返回1
                        if(responseText) {
                            $("#reg").dialog("widget").find("button").eq(1).button("enable");
                            $("#loading").css("background","url(img/success.gif) no-repeat 20px center").html("数据新增成功...");
    
                            setTimeout(function() { //一秒之后执行该function代码
                                $("#loading").dialog("close");
                                $("#reg").dialog("close");
                                $("#reg").resetForm(); //重置表单
                                $("#reg span.star").html("*").removeClass("succ");
                                $("#loading").css("background","url(img/loading.gif) no-repeat 20px center").html("数据交互中...");
                            }, 1000);
                        }
                    }
                });
            },
            //错误提示出现,对话框高度增加,出现滚动条,所以应去除滚动条
            //每次激活错误,都会触发此属性
            showErrors:function(errorMap, errorList) {
                var errors = this.numberOfInvalids();
                if(errors > 0) {
                    $("#reg").dialog("option","height",errors * 20 + 340);
                } else {
                    $("#reg").dialog("option","height",340);
                }
                this.defaultShowErrors(); //执行默认错误
            },
            //高亮显示有错误的元素,变色式
            highlight:function(element,errorClass) {
                $(element).css("border","1px solid #630");
                $(element).parent().find("span").html("*").removeClass("succ");
            },
            //恢复默认
            unhighlight:function(element,errorClass) {
                $(element).css("border","1px solid #ccc");
                //element即为<input>控件
                //$(element).parent().find("span").html("ok");
                $(element).parent().find("span").html("&nbsp;").addClass("succ");
            },
            errorLabelContainer:"ol.reg_error",
            wrapper:"li",
            rules:{
                user:{
                    required:true,
                    minlength:2
                },
                pass:{
                    required:true,
                    minlength:6
                },
                email:{
                    required:true,
                    email:true
                },
                date:{
                    date:true
                }
            },
            messages:{
                user:{
                    required:"账号不得为空!",
                    minlength:"账号不得小于{0}位!"
                },
                pass:{
                    required:"密码不得为空!",
                    minlength:"密码不得小于{0}位!"
                },
                email:{
                    required:"邮箱不得为空!",
                    email:"请输入正确的邮箱地址!"
                }
            }
        });
    
        $("#date").datepicker({
            changeMonth:true,
            changeYear:true,
            yearSuffix: ' ',
            maxDate:0, 
            yearRange:"1950:2020",
        });
    
        $("#email").autocomplete({
            delay:0,
            autoFocus:true,
            source:function(request,response) {
                var hosts = ['qq.com','163.com','126.com','sina.com.cn','gmail.com','hotmail.com'],
                    term = request.term, //获取用户输入的内容
                    name = term, //邮箱的用户名,如i_beautiful
                    host = '', //邮箱的域名,如sina.com.cn
                    ix = term.indexOf('@'), //@的位置
                    result = []; //最终呈现的邮箱列表
    
                result.push(term);
                if(ix > -1) {
                    name = term.slice(0, ix);
                    host = term.slice(ix + 1);
                }
                if(name) {
                    var findedHosts = (host ? $.grep(hosts, function(value, index) {
                            return value.indexOf(host) > -1; }) : hosts),
                        findedResult = $.map(findedHosts, function(value, index) {
                            return name + "@" + value; 
                        });
                    result = result.concat(findedResult);
                }
                response(result);
            }
        });
    
    });
    View Code
  • 相关阅读:
    面对满足正态分布的事情,我们如何增加成功概率
    《灭火:美国金融危机及其教训》笔记
    《失控:机器、社会与经济的新生物学》笔记
    外推谬误
    迎接未来,我们可以做什么
    怎样理解帝国与王朝的兴衰,以及它对组织管理有何启示?
    vue中$emit的用法,父子组件传值及页面跳转之间传值
    SharePoint Online 调用PnP.js 搜索返回结果不完整
    SharePoint REST API 的 Expand 方法
    SharePoint Online PnPjs 批量更新项目
  • 原文地址:https://www.cnblogs.com/yerenyuan/p/5467427.html
Copyright © 2020-2023  润新知