我们在前面几篇文章中一直采用最精简的方式创建Ajax的核心XMLHttpRequest对象
1 |
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject( 'Microsoft.XMLHTTP' ); |
没有考虑其可能出现的异常,即创建失败。其实个人认为以上创建方式创建失败的几率非常之少,起码在IE6/7/8/Firefox/Safari/Chrome/Opera如此,其它浏览器就不知了。
但作为一个基础库还是完善下,如果出现创建失败,failure的第二个参数msg将会被赋值为"create xhr failed"。
如下
03 |
return new XMLHttpRequest(); |
06 |
return new ActiveXObject( 'Msxml2.XMLHTTP' ); |
09 |
return new ActiveXObject( 'Microsoft.XMLHTTP' ); |
11 |
failure( null , 'create xhr failed' ,e); |
完整源码
003 |
function request(url,opt){ |
006 |
var async = opt.async !== false , |
007 |
method = opt.method || 'GET' , |
008 |
type = opt.type || 'text' , |
009 |
encode = opt.encode || 'UTF-8' , |
010 |
timeout = opt.timeout || 0, |
011 |
data = opt.data || null , |
012 |
success = opt.success || fn, |
013 |
failure = opt.failure || fn; |
014 |
method = method.toUpperCase(); |
015 |
if (data && typeof data == 'object' ){ |
016 |
data = _serialize(data); |
018 |
if (method == 'GET' && data){ |
019 |
url += (url.indexOf( '?' ) == -1 ? '?' : '&' ) + data; |
022 |
var xhr = function (){ |
024 |
return new XMLHttpRequest(); |
027 |
return new ActiveXObject( 'Msxml2.XMLHTTP' ); |
030 |
return new ActiveXObject( 'Microsoft.XMLHTTP' ); |
032 |
failure( null , 'create xhr failed' ,e); |
038 |
var isTimeout = false , timer; |
039 |
if (async && timeout>0){ |
040 |
timer = setTimeout( function (){ |
045 |
xhr.onreadystatechange = function (){ |
046 |
if (xhr.readyState == 4 && !isTimeout){ |
047 |
_onStateChange(xhr, type, success, failure); |
051 |
xhr.open(method,url,async); |
052 |
if (method == 'POST' ){ |
053 |
xhr.setRequestHeader( 'Content-type' , 'application/x-www-form-urlencoded;charset=' + encode); |
058 |
function _serialize(obj){ |
062 |
if (val.constructor == Array){ |
063 |
for ( var i=0,len=val.length;i<len;i++){ |
064 |
a.push(k + '=' + encodeURIComponent(val[i])); |
067 |
a.push(k + '=' + encodeURIComponent(val)); |
072 |
function _onStateChange(xhr,type,success,failure){ |
073 |
var s = xhr.status, result; |
074 |
if (s>= 200 && s < 300){ |
077 |
result = xhr.responseText; |
080 |
result = function (str){ |
081 |
return ( new Function( 'return ' + str))(); |
085 |
result = xhr.responseXML; |
090 |
failure(xhr, 'request timeout' ); |
092 |
failure(xhr,xhr.status); |
097 |
var Ajax = {request:request}, types = [ 'text' , 'json' , 'xml' ]; |
098 |
for ( var i=0,len=types.length;i<len;i++){ |
099 |
Ajax[types[i]] = function (i){ |
100 |
return function (url,opt){ |
103 |
return request(url,opt); |
(责任编辑:admin) |