javscript创建ajax请求的详细步骤,兼容IE,可设置请求头,超时,读取响应头
创建ajax XHR对象
window.onerror = function(e) //屏蔽错误
{
if(!!window.console)
{
window.console.log(e);
}
}
function createAjax()
{
var xhr = null;
if(!!window.XMLHttpRequest)
{
xhr = new window.XMLHttpRequest();
}else{
try{ //IE7+
xhr = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
//IE6-
try { xhr = new ActiveXObject(“Microsoft.XMLHTTP”);} catch (e) { }
}
}
return xhr;
}
2.创建请求头设置函数(注意,该函数必须在xhr.open之后调用,否则会出错)
//设置ajax请求头
function setAjaxHeaders(xhr,headers)
{
if(typeof(xhr)==’object’ && typeof(headers)==’object’)
{
for (var name in headers)
{
if(typeof(headers[name])!=’function’)
{
xhr.setRequestHeader(name,headers[name]);
}
};
}
xhr.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded”);
xhr.setRequestHeader(“x-request-with”,”xmlhttprequest”);
}
3.设置超时(注意:如果是异步请求,不允许设置超时时间,即超时只能等于0)
//设置请求超时
function setAjaxTimeout(xhr,millisecodes)
{
if(typeof(xhr)==’object’ && typeof(millisecodes)==’number’)
{
xhr.timeout = millisecodes;
}
}
4.设置回调
//设置回调函数
function setAjaxCallback(xhr,success,failed,abort)
{
if(typeof(xhr)==’object’)
{
xhr.onreadystatechange = function(args)
{
if(xhr.readyState==xhr.DONE)
{
var respinfo = {
‘xhr’:xhr,
‘status’:xhr.status,
‘headers’:xhr.getAllResponseHeaders(),
data:xhr.responseText
};
success(respinfo);
}else{
failed({‘xhr’:xhr,msg:arguments});
}
}
xhr.ontimeout = function(args)
{
failed(arguments);
}
xhr.onabort = function(args)
{
abort({‘xhr’:xhr});
}
}
}
5.添加一些辅助函数
//请求参数拼接
function httpBuildQuery(data)
{
var queryString = ”;
if(typeof(data)==’object’)
{
for (var name in data)
{
if(typeof(data[name])!=’function’)
{
queryString +=name+’=’+data[name]+’&’;
}
};
}
else if(typeof(data)==’string’)
{
queryString = data;
}
if(queryString.lastIndexOf(‘&’)==0 && queryString.length>0)
{
queryString = queryString.substring.substring(0,queryString.length-1);
}
return queryString;
}
//参数扩展,类似jQuery.extend
function initParams(src,o)
{
if(typeof(src)==’object’ && typeof(o)==’object’)
{
for (var name in src) {
if(typeof(o[name])!=’undefined’ && typeof(o[name])!=’function’)
{
src[name] = o[name];
}
};
}
return src;
}
6.发送请求
function sendAjaxRequest(xhr,url,settings)
{
var params = {
‘method’:’get’,
‘sync’:true,
‘timeout’:15*1000,
‘headers’:null,
‘data’:null
};
params = initParams(params,settings);
if(typeof(xhr)==’object’)
{
//ajax异步请求不允许设置超时时间大于0
var times = params[‘sync’]?0:params[‘timeout’];
setAjaxTimeout(xhr,times);
var queryString = httpBuildQuery(params[‘data’]);
if(params[‘method’].toUpperCase()==’GET’)
{
if(url.indexOf(‘?’)==-1)
{
queryString = ‘?’+queryString;
}
xhr.open(‘GET’, url+queryString, params[‘sync’]);
if(xhr.readyState== xhr.OPENED)
{
setAjaxHeaders(xhr,params[‘headers’]);
}
xhr.send(null);
}else{
xhr.open(‘POST’, url, params[‘sync’]);
if(xhr.readyState== xhr.OPENED)
{
setAjaxHeaders(xhr,params[‘headers’]);
}
xhr.send(queryString);
}
}
}
————————————-
用法演示
var xhr = createAjax();
setAjaxCallback(xhr,function(args){
console.log(arguments);
},function(args){
console.error(arguments);
},function(args){
console.info(arguments);
});
sendAjaxRequest(xhr,’http://localhost/search’,{‘data’:{‘keywords’:’123′}});
————————————-
貌似比jQuery有点复杂了,本来想着疯转成对象来着,时间原因,不封装了,有兴趣的读者可以修改修改,变成2中常用的方式
连缀函数式ajax请求
ajax请求对象
try doing it