原生Ajax发送请求

      ajax  get&post

1.使用get发送请求,会有请求缓存

  1)什么叫请求缓存,请求信息相同浏览器不会再想服务器发送请求,导致访问服务器失败。

  2)解决:将随机数添加到请求路径后面参数传递过去,Math.Random(),可以避免缓存的问题。

2.使用post发送请求,安全性高,解决乱码容易,速度次于get,传递方式post,传递参数在最后发送请求的时候传递

 因为get是在地址栏里传递参数,安全性低,传递方式不同。

  var v_data="name="+obj.value;  //传递多个参数 v_data="name="+obj.value+"&possword="+xxxxx
  xmlHttpRequest.send(v_data);

//创建异步引擎对象,支持IE7以上,IE6以下new ActiveXObject('Microsoft.XMLHTTP');

 

 

 

  function createXMlHttpRequest(){
    if(window.XMLHttpRequest){
    return new XMLHttpRequest();
    }
  }

//回调

function callBack(){
  if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200){

  //responseText响应页面的内容
  var date=xmlHttpRequest.responseText;
  if(date==1){
      document.getElementById("message").innerHTML='<font color="red">此账号不能用!</font>';
    }else{
      document.getElementById("message").innerHTML='<font color="green">账号可以用</font>';
    }
  }
}

  readyState的状态属性值

  0-未初始化,尚未调用open()方法;
  1-启动,调用了open()方法,未调用send()方法;
  2-发送,已经调用了send()方法,未接收到响应;
  3-接收,已经接收到部分响应数据;
  4-完成,已经接收到全部响应数据;

  Status http的状态属性值

  200-请求正常响应

  404没有资源

  500内部错误

function checkName(obj){

//赋值引擎对象
  xmlHttpRequest=createXMlHttpRequest();

//onreadystatechange用于指向回调方法的引用,clallBack()加了括号的是方法的调用
  xmlHttpRequest.onreadystatechange=callBack;

//参数1:请求方式get&post,参数2:请求路径及传递的参数,请求参数,参数3:true异步提交,false:同步提交,默认值为true,false会阻塞线程
  xmlHttpRequest.open("GET","CheckName.do?name="+obj.value,true);

//头文设置
  xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

//使用异步引擎发送请求
  xmlHttpRequest.send();
}

猜你喜欢

转载自www.cnblogs.com/J-Joyce/p/9185767.html