本文共 1445 字,大约阅读时间需要 4 分钟。
/** * 发送ajax请求 * @type {Object} * 使用方法如下: * $ajax.request( * method: "post", //请求方式 * url: "index.php", //请求的服务器地址 * data: "name=itbsl&age=20",//请求时携带的参数 * dataType: "xml", //期望服务器回应的数据 * callback: function(res) { //请求成功后的回调函数 * //处理数据 * } * ); */var $ajax = { request: function(obj) { //创建对象 var xmlhttp; if(window.XMLHttpRequest) { //code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { //code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //建立连接 if(obj.method == 'get') { xmlhttp.open(obj.method, obj.url+"?"+obj.data+"&"+Math.random(), true); xmlhttp.send(); } if(obj.method == 'post') { xmlhttp.open(obj.method, obj.url, true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send(obj.data); } //监视请求的状态 xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { if(obj.dataType == 'xml') { obj.callback(xmlhttp.responseXML); } else if(obj.dataType == 'text') { eval("var res = " + xmlhttp.responseText); obj.callback(res); } } } }} 转载地址:http://ybwyz.baihongyu.com/