AJAX的post和get

2019-05-17  本文已影响0人  Mr君
ajax步骤
post和get的区别
代码
function postMethod(data){

    var xhr = new XMLHttpRequest();

    //不用担心缓存问题
    xhr.open( "post", "example.php", true );

    //必须设置,否则服务器端收不到参数
    xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

    xhr.onreadystatechange = function(){

        if( xhr.readyState = 4 && xhr.status == 200 ){
            document.getElementById("result").innerHTML = xhr.responseText;
        }
    }

    //发送请求,要data数据
    xhr.send( data );

}
function getMethod(data){
  var xhr = new XMLHttpRequest();

  //添加参数,以求每次访问不同的url,以避免缓存问题
  xhr.open( "get", "example.php?data=" + encodeURTComponent( data)  + "&random=" + Math.random(), true );

  xhr.onreadystatechange = function(){

      if( xhr.readyState == 4 && xhr.status == 200 ){

          document.getElementById("result").innerHTML = xhr.responseText;
      }
  }

  //发送请求,参数为null
  xhr.send( null );
}
上一篇下一篇

猜你喜欢

热点阅读