// javascript document//表示 ajax 调用方式 function createxhr() { if (typeof xmlhttprequest != 'undefined') { return new xmlhttprequest(); } else if (typeof activexobject != 'undefined') { var version = [ 'msxml2.xmlhttp.6.0', 'msxml2.xmlhttp.3.0', 'msxml2.xmlhttp' ]; for (var i = 0; version.length; i ++) { try { return new activexobject(version[i]); } catch (e) { //跳过 } } } else { throw new error('您的系统或浏览器不支持xhr对象!'); } } //名值对转换为字符串 function paramsjoin(data) { var arr = []; for (var i in data) { arr.push(encodeuricomponent(i) + '=' + encodeuricomponent(data[i])); } return arr.join('&'); } //封装ajax function ajax(obj) { var xhr = createxhr(); obj.url = obj.url + '?rand=' + math.random(); obj.data = paramsjoin(obj.data); if (obj.method === 'get') obj.url += obj.url.indexof('?') == -1 ? '?' + obj.data : '&' + obj.data; if (obj.async === true) { xhr.onreadystatechange = function () { if (xhr.readystate == 4) { callback(); } }; } xhr.open(obj.method, obj.url, obj.async); if (obj.method === 'post') { xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded'); xhr.send(obj.data); } else { xhr.send(null); } if (obj.async === false) { callback(); } function callback() { if (xhr.status == 200) { obj.success(xhr.responsetext); //回调传递参数 } else { alert('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statustext); } } }