浅谈ajax-post方法

最近在学习ajax,整理了一下post方法
注意php文件必须允许在服务器环境才能成功

//先封装一个ajax-post方法
新建ajax-post.js
function obj2str(obj){
   obj.t= new Date().getTime();
   var res = []
   for(var key in obj){
    res.push(encodeURLComponent(key) + "=" +
    encodeURLComponent(obj[key]));
   }
   return res.join("&")
}
function ajax(type,url,obj,timeout,success,error){
  var str = obj2str(obj);
  var xmlhttp,timer;
  if(window.XMLHttpRequest){
   xmlhttp = newXMLHttpRequest();
  }else{
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP);
 }
 if(type==="GET'){
  xmlhttp.open(type,url+"?"+str,true);
   xmlhttp.send();
 }else{
  xmlhttp.open(type, url, true);
    // 注意点:以下代码必须放在open和sen之间
    xmlhttp.setRequestHeader("Content-type",         "application/x-www-form-urlencoded");
    // 发送请求
    xmlhttp.send(str);
 }
  // 监听状态变化
  xmlhttp.onreadystatechange = function (ev2) {
    if (xmlhttp.readyState === 4) {
      clearInterval(timer)
      if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304) {
        success(xmlhttp)
      } else {
        error(xmlhttp)
      }
    }
  }
  // 判断外部是否传入了超时时间
  if (timeout) {
    timer = setInterval(function () {
      console.log('请求中断')
      xmlhttp.abort();
      clearInterval(timer);
    }, timeout)
  }
}

然后调用方法 post.html

"userName":"zs"
},3000,function(xmlhttp){
console.log(xmlhttp.responseText)
},function(xmlhttp){
console.log("error")
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值