function openLink(o){ var XHR, config = (typeof o === 'object' && o!=null)?o : {}, scope = config.scope||window, method = config.method||'GET', cb = typeof config.callback === 'function' ? config.callback : function(){}, url = config.url, params = config.params||{}, p = null, addURLParam = function(url,key,value){ url += (url.indexOf('?') == -1 ? '?' : '&'); url += encodeURIComponent(key) + '=' + encodeURIComponent(value); return url; }, timeout = 30000;//30s if(typeof url !== 'string'){ throw new Error('配置的请求地址错误!'); } if(typeof XMLHttpRequest != 'undefined'){ XHR = new XMLHttpRequest(); }else if(typeof ActiveXObject != 'undefined'){ var versions = ['MSXML2.XMLHTTP.3.0','Msxml2.XMLHTTP.6.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP']; for(var i=0,len=versions.length;i<len;i++){ try{ XHR = new ActiveXObject(versions[i]); break; }catch(ex){ } } }else{ throw new Error('您的浏览器不能创建XHR对象!'); } var t = setTimeout(function(){ XHR.abort(); throw new Error('timeout!'); },timeout); XHR.onreadystatechange = function(){ if(XHR.readyState == 4){ if((XHR.status >= 200 && XHR.status < 300) || XHR.status == 304){ //success //XHR.responseText clearTimeout(t); cb.call(scope,XHR.responseText); }else{ //exception throw new Error('Request is unsuccessfull: '+ XHR.status); } } } if(method.toUpperCase() == 'GET'){ for(var f in params){ url = addURLParam(url,f,params[f]); } }else if(method.toUpperCase() == 'POST'){ var a = []; for(var f in params){ a.push(f+'='+encodeURIComponent(params[f])); } p = a.join('&'); } XHR.open(method,url,true); XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); XHR.send(p); }
使用:
<script type="text/javascript">
openLink({
method : 'post',
url : 'data/test.do',
params : {e:'中文abc123',r:5},
callback : function(responseText){
var o = eval('('+responseText+')');
alert(o.success);
}
});
</script>