知问前端——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>
采用对话框式:
$("#loading").dialog({
autoOpen:false,
modal:true,
closeOnEscape:false, //按下Esc无效
resizable:false,
draggable:false,
width: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:;
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:;
}
#header .header_main {
width: 800px;
height: 40px;
margin: 0 auto;
}
#header .header_main h1 {
font-size: 20px;
margin:;
padding:;
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:;
}
#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:;
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;
}
三、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,
width: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,
width: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(" ").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);
}
});
});
知问前端——Ajax提交表单的更多相关文章
- Jquery ajax提交表单几种方法
在jquery中ajax提交表单有post与get方式,在使用get方式时我们可以直接使用ajax 序列化表单$('#表单ID').serialize();就行了,下面我来介绍两个提交表单数据的方法. ...
- Validator验证Ajax提交表单的方法
Validator验证Ajax提交表单的方法 转自:http://hunanpengdake.iteye.com/blog/1671360 当我们在一些稍微复杂的业务时,可能会遇到需要多个表单form ...
- lavarel框架中如何使用ajax提交表单
开门见山,因为laravel以post形式提交数据时候需要加{{csrf_field()}}防止跨站攻击,所以当你用ajax提交表单时候自然也要加 在网上看了很多的解决方式,我是用下面这种方法解决的: ...
- Jquery ajax提交表单几种方法详解
[导读] 在jquery中ajax提交表单有post与get方式,在使用get方式时我们可以直接使用ajax 序列化表单$( 表单ID) serialize();就行了,下面我来介绍两个提交表单数据的 ...
- ajax提交表单序列化(serialize())数据
知识点: $("#form").serialize();将表单数据序列化为标准URL编码文本字符串(key1=value1&key2=value2…). 以下用一个例子来演 ...
- jquery实现ajax提交表单
一般情况下,我们提交form表单采用的是submit的方法,典型的场景如下. <form id="thisForm" method="post" acti ...
- ajax提交表单、ajax实现文件上传
ajax提交表单.ajax实现文件上传,有需要的朋友可以参考下. 方式一:利用from表单的targer属性 + 隐藏的iframe 达到类似效果, 支持提交含有文件和普通数据的复杂表单 方式二:使用 ...
- Ajax提交表单初接触
<!doctype html> <html class="no-js"> <head> <meta charset="utf-8 ...
- KindEditor:Ajax提交表单时获取不到HTML内容
当用Ajax提交表单时,KindEditor的内容获取不到,HTML数据获取不了 原因:当ajax提交时,KindEdito的HTML数据还没有同步到表单中来,那怎么去获取HTML数据呢? ----- ...
随机推荐
- 词频统计 SPEC 20170914 1 1 1 1 1
功能1 小文件输入,为表明程序能跑,结果真实而不是迫害老五,请他亲自键盘在控制台下输入命令. #include<stdio.h> #include<string.h> #inc ...
- 第十九次ScrumMeeting会议
第十九次Scrum Meeting 时间:2017/12/9 地点:三公寓大厅 人员:蔡帜 王子铭 游心 解小锐 王辰昱 李金奇 杨森 陈鑫 赵晓宇 照片: 目前工作进展 名字 今日 明天的工作 蔡帜 ...
- 自学系列--git的基础简介
上学期第一次接触git,感觉挺难的,我们都知道这个非常重要,自己对git也自学了一段时间,下面这是对自学内容的总结,拿出来和大家一块交流一下,让我们一起成长吧! 一 git简介 Git是一个开源的分布 ...
- 软工实践Alpha冲刺(2/10)
队名:我头发呢队 组长博客 作业博客 杰(组长) 过去两天完成了哪些任务 查看了讯飞开放平台的sdk 查阅了Google Material Design 2的官方文档 接下来的计划 继续打磨UI界面: ...
- String 和 CharSequence 关系与区别
String 继承于CharSequence,也就是说String也是CharSequence类型. CharSequence是一个接口,它只包括length(), charAt(int index) ...
- QWidget一生,从创建到销毁事件流
版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址: 本文标题:QWidget一生,从创建到销毁事件流 本文地址:http://techieliang ...
- GC是什么?为什么要有GC
GC:Garbage Collection 垃圾收集器. GC就是对“不可达“的对象进行回收,释放内存. Java内存的管理实际上就是对对象的管理,其中包括对对象的分配和回收. 对于程序员来说,分配对 ...
- 提升MyEclipse运行速度
修改MyEclipse.ini文件中的,将-vmargs后面的参数修改为 -Xms256m -Xmx768m -XX:PermSize=128M -XX:MaxNewSize=256m -XX:Max ...
- [剑指Offer] 57.二叉树的下一个结点
题目描述 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回.注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针. /* struct TreeLinkNode { in ...
- 关于Python的 a, b = b, a+b
Python中有一种写法:多个值同时赋给多个变量,如:a, b = b, a+b 1. A写法 a = 0, b = 1 a, b = b, a+b print a, b #结果为:1 1 这种写法, ...