方法一:(类似jQuery的封装方法)
1、ajax函数封装:
/*
*author: Ivan
*date: 2014.06.01
*参数说明:
*opts: {'可选参数'}
**method: 请求方式:GET/POST,默认值:'GET';
**url: 发送请求的地址, 默认值: 当前页地址;
**data: string,json;
**async: 是否异步:true/false,默认值:true;
**cache: 是否缓存:true/false,默认值:true;
**contentType: HTTP头信息,默认值:'application/x-www-form-urlencoded';
**success: 请求成功后的回调函数;
**error: 请求失败后的回调函数;
*/
function ajax(opts){
//一.设置默认参数
var defaults = {
method: 'GET',
url: '',
data: '',
async: true,
cache: true,
contentType: 'application/x-www-form-urlencoded',
success: function (){},
error: function (){}
}; //二.用户参数覆盖默认参数
for(var key in opts){
defaults[key] = opts[key];
} //三.对数据进行处理
if(typeof defaults.data === 'object'){ //处理 data
var str = '';
var value = '';
for(var key in defaults.data){
value = defaults.data[key];
if( defaults.data[key].indexOf('&') !== - ) value = defaults.data[key].replace(/&/g, escape('&')); //对参数中有&进行兼容处理
if( key.indexOf('&') !== - ) key = key.replace(/&/g, escape('&')); //对参数中有&进行兼容处理
str += key + '=' + value + '&';
}
defaults.data = str.substring(, str.length - );
} defaults.method = defaults.method.toUpperCase(); //处理 method defaults.cache = defaults.cache ? '' : '&' + new Date().getTime() ;//处理 cache if(defaults.method === 'GET' && (defaults.data || defaults.cache)) defaults.url += '?' + defaults.data + defaults.cache; //处理 url //四.开始编写ajax
//1.创建ajax对象
var oXhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
//2.和服务器建立联系,告诉服务器你要取什么文件
oXhr.open(defaults.method, defaults.url, defaults.async);
//3.发送请求
if(defaults.method === 'GET')
oXhr.send(null);
else{
oXhr.setRequestHeader("Content-type", defaults.contentType);
oXhr.send(defaults.data);
}
//4.等待服务器回应
oXhr.onreadystatechange = function (){
if(oXhr.readyState === ){
if(oXhr.status === )
defaults.success.call(oXhr, oXhr.responseText);
else{
defaults.error();
}
}
};
}
2、ajax函数调用:
//调用ajax函数 ajax({ url: '1.php', data: {name: 'ivan', sex: 'male', age: ''}, success: function (data){ alert('返回数据是:' + data); } }); ajax({ url: '1.php', data: 'name=ivan&sex=male&age=23', cache: false, success: function (data){ alert('返回数据是:' + data); } });
转摘于:http://www.cnblogs.com/Ivangel/p/3825701.html?utm_source=tuicool&utm_medium=referral 感谢原作者
方法二:
1、ajax封装
//ajax封装
function Ajax(type, url, data, success, failed){
// 创建ajax对象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP')
} var type = type.toUpperCase();
// 用于清除缓存
var random = Math.random(); if(typeof data == 'object'){
var str = '';
for(var key in data){
str += key+'='+data[key]+'&';
}
//method=get&url=
data = str.replace(/&$/, '');
} if(type == 'GET'){
if(data){
xhr.open('GET', url + '?' + data, true);
} else {
xhr.open('GET', url + '?t=' + random, true);
}
xhr.send(); } else if(type == 'POST'){
xhr.open('POST', url, true);
// 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
} // 处理返回数据
xhr.onreadystatechange = function(){
if(xhr.readyState == ){
if(xhr.status == ){
success(xhr.responseText);
} else {
if(failed){
failed(xhr.status);
}
}
}
}
}
2、ajax调用
//调用
Ajax('get','check.php',sendData,function(data) {}
3、ajax注册例子如下
//例子 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ajax注册</title>
</head>
<body>
<form method="post" action="http://www.mytest.com/ajax-09.php" onsubmit="return checkform();"> 用户名:<input type="text" name="username" id="username" onfocus="clearTips()" onblur="checkName();" />
<br/><br/> 密 码:<input type="password" name="userpass1" id="userpass1" onblur="checkPassFirst();" onfocus="clearTips();"/>
<br/><br/> 确认密码:<input type="password" name="userpass2" id="userpass2" onblur="checkPass();" onfocus="clearTips();" />
<br/><br/> 邮箱:<input type="text" name="useremail" id="useremail" onblur="checkEmail();" onfocus="clearTips();" />
<br/><br/> 手机:<input type="text" name="usermobile" id="usermobile" onfocus="clearTips();" onblur="checkMobile();"/><input type="button" value="获取手机验证码" id="mobilebtn" style="display:none;" onclick="getMobileCode();"/>
<br/><br/> 验证码:<input type="text" name="vcode" id="vcode" onblur="checkCode();" onfocus="clearTips();"/>
<img id="code" src="http://www.mytest.com/ajax/code.php" style="width:80;height:24px;border:0;" onclick="changeCode();"/>
<br/><br/> <p style="clear:both;width:500px;color:red;display:none;" id="tips" error=""> </p>
<input type="submit" value="注册" id="submit"/>
</form>
<script>
function checkform() {
var name = document.getElementById('username').value;
if (name.length <= ) {
showTips('用户名不能为空');
return false;
} var pass = document.getElementById('userpass1').value;
if (pass.length <= ) {
showTips('密码不能为空');
return false;
} var pass2 = document.getElementById('userpass2').value;
if (pass2.length <= ) {
showTips('确认密码不能为空');
return false;
} if (pass != pass2) {
showTips('两次密码输入不一致');
return false;
} var email = document.getElementById('useremail').value;
if (email.length <= ) {
showTips('邮箱不能为空');
return false;
}
var emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
if( !emailReg.test(email) ){
showTips('邮箱输入有误,请重新输入')
return false;
} var mobile = document.getElementById('usermobile').value;
if (mobile.length <= ) {
showTips('手机号不能为空');
return false;
} var regu =/^[][|||][-]{}$/gi;
var re = new RegExp(regu);
if (!re.test(mobile)) {
showTips('手机号输入有误,请重新输入')
return false;
} var code = document.getElementById('vcode').value;
if (code.length <= ) {
showTips('验证码不能为空');
return false;
} return true;
} function clearTips(){
document.getElementById('tips').style.display = "none";
document.getElementById('tips').innerHTML = '';
document.getElementById('submit').disabled = false;
} function showTips(msg){
tipObj = document.getElementById('tips');
tipObj.style.display = "block";
tipObj.innerHTML = msg;
document.getElementById('submit').disabled = true;
} function loading(){
tipObj = document.getElementById('tips');
tipObj.style.display = "block";
tipObj.innerHTML = '加载中...';
} function removeLoading(){
tipObj = document.getElementById('tips');
tipObj.innerHTML = '';
tipObj.style.display = "none";
} function checkName(){
var name = document.getElementById('username').value;
if(isNull(name)) {
showTips('请输入用户名');
}
loading();
var sendData = {username:name,action:'checkname'};
Ajax('get','check.php',sendData,function(data) {
removeLoading();
var user = eval('('+data+')')
if (user.id) {
showTips('用户名已被占用,请重新输入用户名');
}
}, function(data){ showTips('ajax请求错误');
}); } function checkEmail(strEmail) {
var strEmail = document.getElementById('useremail');
var emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
if( !emailReg.test(strEmail.value) ){
showTips('邮箱输入有误,请重新输入')
return false;
}
} function changeCode(){
var url = document.getElementById('code').src ;
var rand = Math.floor(Math.random() * ( + ));
url += '?' + rand;
document.getElementById('code').src = url;
} function checkMobile(s){
var obj = document.getElementById('usermobile');
var regu =/^[][|||][-]{}$/gi;
var re = new RegExp(regu);
if (!re.test(obj.value)) {
showTips('手机号输入有误,请重新输入') var obj = document.getElementById('mobilebtn');
obj.style.display = 'none';
obj.disabled = true;
return false;
}
var obj = document.getElementById('mobilebtn');
obj.style.display = 'block';
obj.disabled = false;
} function getMobileCode(){
var obj = document.getElementById('usermobile');
var regu =/^[][|||][-]{}$/gi;
var re = new RegExp(regu);
if (!re.test(obj.value)) {
showTips("手机号输入有误,请重新输入")
return false;
}
sendData = {mobile:obj.value, action:"getcode"}
//ajax调用
Ajax("get","check.php",sendData, function(data){
tipObj = document.getElementById('tips');
tipObj.style.display = "block";
tipObj.innerHTML = "手机验证码是:" + data;
}, function(data){
showTips('手机验证码获取错误') ;
});
} function checkPassFirst(){
var pass = document.getElementById('userpass1').value;
if (pass.length <= ) {
showTips('请输入密码');
return false;
} } function checkPass(){
var obj1 = document.getElementById('userpass1');
var obj2 = document.getElementById('userpass2');
if (obj2.value.length <= ) {
showTips('请输入确认密码');
return false;
}
if (obj1.value != obj2.value ) {
showTips('密码与确认密码不对,请重新输入密码');
return false;
}
} function checkCode(){
var obj1 = document.getElementById('vcode');
if (obj1.value.length <= ) {
showTips('请输入验证码');
return false;
}
if (obj1.value.length != ) {
showTips('请输入正确的验证码');
return false;
}
} function isNull( str ){
if ( str == "" ) return true;
var regu = "^[ ]+$";
var re = new RegExp(regu);
return re.test(str);
} function addCookie(objName,objValue,objHours){//添加cookie
var str = objName + "=" + escape(objValue);
if(objHours > ){//为0时不设定过期时间,浏览器关闭时cookie自动消失
var date = new Date();
var ms = objHours**;
date.setTime(date.getTime() + ms);
str += "; expires=" + date.toGMTString();
}
document.cookie = str;
alert("添加cookie成功");
} function getCookie(objName){//获取指定名称的cookie的值
var arrStr = document.cookie.split("; ");
for(var i = ;i < arrStr.length;i ++){
var temp = arrStr[i].split("=");
if(temp[] == objName) return unescape(temp[]);
}
} function delCookie(name){//为了删除指定名称的cookie,可以将其过期时间设定为一个过去的时间
var date = new Date();
date.setTime(date.getTime() - );
document.cookie = name + "=a; expires=" + date.toGMTString();
} //ajax封装
function Ajax(type, url, data, success, failed){
// 创建ajax对象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP')
} var type = type.toUpperCase();
// 用于清除缓存
var random = Math.random(); if(typeof data == 'object'){
var str = '';
for(var key in data){
str += key+'='+data[key]+'&';
}
//method=get&url=
data = str.replace(/&$/, '');
} if(type == 'GET'){
if(data){
xhr.open('GET', url + '?' + data, true);
} else {
xhr.open('GET', url + '?t=' + random, true);
}
xhr.send(); } else if(type == 'POST'){
xhr.open('POST', url, true);
// 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
} // 处理返回数据
xhr.onreadystatechange = function(){
if(xhr.readyState == ){
if(xhr.status == ){
success(xhr.responseText);
} else {
if(failed){
failed(xhr.status);
}
}
}
}
}
</script>
</body>
</html>