Ajax

aInpt.onclick=function(){
  // 1. 第一步
  if(window.XMLHttpRequest)
  {
    var oAjax=new XMLHttpRequest(); //兼容标准IE 谷歌 火狐
  }
  else{
    var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
  }
  // 2. 链接服务器 open(方法, 文件名, 异步传输)
  oAjax.open('GET','data.txt?t='+new Date().getTime(),true);
  // 3. 发送请求
  oAjax.send();
  //4 接收返回
  oAjax.onreadystatechange=function(){
    if(oAjax.readyState==4) //读取完成
    {
      if(oAjax.status==200)
      {
        alert('数据接收');
      }
      else{
        alert('返回失败');
      }
    }
  }
}

 

 

//函数封装

function ajax(url, fnSucc, fnFaild)
{
  //1.创建Ajax对象
  if(window.XMLHttpRequest)
  {
    var oAjax=new XMLHttpRequest();
  }
  else
  {
    var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
  }

  //2.连接服务器(打开和服务器的连接)
  oAjax.open('GET', url, true);


  //3.发送
  oAjax.send();

  //4.接收
  oAjax.onreadystatechange=function ()
  {
    if(oAjax.readyState==4)
    {
      if(oAjax.status==200)
      {
        //alert('成功了:'+oAjax.responseText);
        fnSucc(oAjax.responseText);
      }
      else
      {
        //alert('失败了');
        if(fnFaild)
        {
          fnFaild();
        }
      }
    }
  };
}

posted @ 2015-11-30 16:00  zhengyan_web  阅读(136)  评论(0编辑  收藏  举报