封装一个简单的Ajax函数

 

/**
* Ajax操作函数
*
* @param url -- 服务器端页面地址
* @param param -- 参数,类似 'user=123&id=100'
* @param method -- 请求服务器端的方法,Get和Post两种,默认是GET
* @param response -- 是否获取服务器端返回的结果,默认是true
*/
function ajax( url, param, method, response ){
//set default value
param = typeof(param)=='undefined' ? '' : param;
method = typeof(method)=='undefined' ? 'GET' : method;
response = typeof(response)=='undefined' ? true : response;

//get ajax object
var ajax = null;
try {
   ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
   try {
    ajax = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (E) {
    ajax = null;
   }
}
if (!ajax && typeof XMLHttpRequest!='undefined'){
   ajax = new XMLHttpRequest();
}
if (!ajax){
   alert("Get ajax object failed");
   return false;
}

//send http request
var res = '';
if (method != 'GET'){
   method = 'POST';
}
if (method == 'GET'){
   ajax.open('GET', url + param, true);
   ajax.onreadystatechange = function(){
    if (ajax.readyState==4 && ajax.status==200){
     res = ajax.responseText;
    }
   }
   ajax.send(null);
}
if (method == "POST"){
   ajax.open("POST", url, true);
   ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
   ajax.send(param);
   ajax.onreadystatechange = function() {
    if (ajax.readyState==4 && ajax.status==200) {
     res = ajax.responseText;
    }
   }
}
if (response){
   return res;
}
return null;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值