这是我们Ajax实战系列的最后一篇。
ECMAScript 5发布有段时间了,其中就包括了解析JSON的原生API-JSON.parse。许多浏览器已经支持了。主流JS库如JQuery,Ext,Prototype都优先使用JSON.parse,不支持该方法的浏览器则使用new Function或eval。 为何优先使用JSON.parse,我想一个就是性能,原生的总是要快一些吧。此外JSON.parse较eval也更安全。
这里也当然不能落后了,优先使用JSON.parse,不行再用new Function方式。最后失败了会给failure的第二个参数msg赋值为"parse json error"
01 |
result = function (str){ |
03 |
return JSON.parse(str); |
06 |
return ( new Function( 'return ' + str))(); |
08 |
failure(xhr, 'parse json error' ,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; |
081 |
result = function (str){ |
083 |
return JSON.parse(str); |
086 |
return ( new Function( 'return ' + str))(); |
088 |
failure(xhr, 'parse json error' ,e); |
094 |
result = xhr.responseXML; |
099 |
typeof result !== 'undefined' && success(result); |
103 |
failure(xhr, 'request timeout' ); |
105 |
failure(xhr,xhr.status); |
110 |
var Ajax = {request:request}, types = [ 'text' , 'json' , 'xml' ]; |
111 |
for ( var i=0,len=types.length;i<len;i++){ |
112 |
Ajax[types[i]] = function (i){ |
113 |
return function (url,opt){ |
116 |
return request(url,opt); |
(责任编辑:admin) |