表单验证很重要,极其重要。
首先,获取绑定对象的js函数是
function getActivatedObject(e) {
var obj;
if (!e) {
// early version of IE
obj = window.event.srcElement;
} else if (e.srcElement) {
// IE 7 or later
obj = e.srcElement;
} else {
// DOM Level 2 browser
obj = e.target;
}
return obj;
}
连接事件 和响应函数是
function addEventHandler(obj, eventName, handler) {
if (document.attachEvent) {
obj.attachEvent("on" + eventName, handler);
} else if (document.addEventListener) {
obj.addEventListener(eventName, handler, false);
}
}
一般表单的验证函数为
非空的
function fieldIsFilled(e){
var me=getActivatedObject(e);
if(this.value==""){
\\ warn(me,"required");
}else{
\\ unwarn(me,"required");
}
}
是字母的
function fieldIsLetters(e){
var me=getActivatedObject(e);
var nonAlphaChars=/[^a-zA-z]/;
if(nonAlphaChars.test(me.value)){
//desplay an error message
warn(me,"letters");
}else{
unwarn(me,"letters");
}
}
是数字的
function fieldIsNumbers(e){
var me=getActivatedObject(e);
var noNumbericChars=/[^0-9]/;
if(noNumbericChars.test(me.value)){
//desplay an error message
warn(me,"letters");
}else{
unwarn(me,"letters");
}
}
邮箱的格式验证:
function emailIsProper(e){
var me = getActivatedObject(e);
if(!/^[\w\.-_\+]+@[\w-]+(\.\w{2,4})+$/.test(me.value)){
warn(me,"letters");
}else{
unwarn(me,"letters");
}
}
验证举例:
addEventHandler(document.getElementById("email"),"blur",fieldIsFilled);
post方式提交ajax的区别
var url = "register.php";
var requestData="username=" +
escape(document.getElementById("username").value) + "&password=" +
escape(document.getElementById("password1").value) + "&firstname=" +
escape(document.getElementById("firstname").value) + "&lastname=" +
escape(document.getElementById("lastname").value) + "&email=" +
escape(document.getElementById("email").value) + "&genre=" +
escape(document.getElementById("genre").value) + "&favorite=" +
escape(document.getElementById("favorite").value) + "&tastes=" +
escape(document.getElementById("tastes").value);
registerRequest.onreadystatechange = registrationProcessed;
registerRequest.open("POST", url, true);
registerRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
registerRequest.send(requestData);
不需要回调,url不在附加信息,信息自己打包成requestData,要设置发送的文件头,方便服务器解析
registerRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");