ajax方法的封装,get,post方式的注意点

在ajax方法中,get方法和post方法是最常用的两种方法,下面总结了get和post方法在使用中需要注意的几点:

一: ajax的js封装

function ajax(method, url, data, success) {
var xhr = null;
try { 
  xhr = new XMLHttpRequest();
} catch (e) {
   xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
if (method == 'get' && data) { 
  url += '?' + data;
}
xhr.open(method,url,true);
if (method == 'get') {  
 xhr.send();
} else {  
 xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');  
 xhr.send(data);
}
xhr.onreadystatechange = function() {
   if ( xhr.readyState == 4 ) {    
  if ( xhr.status == 200 ) {        
 success && success(xhr.responseText);      
} else {  
       alert('出错了,Err:' + xhr.status); 
     } 
    }
   }
}

二: html代码

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script src="ajax.js"></script>
<script>
window.onload = function() {   
   var oBtn = document.getElementById('btn');    
   oBtn.onclick = function() { 
     ajax('get','getNews.php','',function(data) {     
    var data = JSON.parse( data );   
       var oUl = document.getElementById('ul1');     
    var html = '';    
     for (var i=0; i<data.length; i++) {      
      html += '<li><a href="">'+data[i].title+'</a> 
[<span>'+data[i].date+'</span>]</li>';    
     }  
       oUl.innerHTML = html;    
  });

 setInterval(function() {   
      ajax('get','getNews.php','',function(data) {    
        var data = JSON.parse( data );           
                var oUl = document.getElementById('ul1');         
   var html = '';     
       for (var i=0; i<data.length; i++) {
              html += '<li><a href="">'+data[i].title+'</a> 
                        [<span>'+data[i].date+'</span>]</li>';     
       }       
     oUl.innerHTML = html;   
      });   
   }, 1000);     
    }
}
</script>
</head>
<body>   
<input type="button" value="按钮" id="btn" />  
  <ul id="ul1"></ul>
</body>
</html>

二:get和post方法的注意点:
get方法:
1)get方法在请求完成之后就会在浏览器中产生url缓存,如果请求的后台页面发生变化,而我们使用跟上次相同的地址去访问就会出现访问不到最新的页面,这时候需要在url?后面连接一个随机数,即时间戳

  1. 如果参数中出现中文,那么浏览器解析的时候会把一堆乱码发到后台,解决乱码问题,要使用编码encodeURI
<script>
window.onload = function() {      
var oBtn = document.getElementById('btn');         
oBtn.onclick = function() {           
 var xhr = null;   
   try {   
      xhr = new XMLHttpRequest();    
  } catch (e) {   
      xhr = new ActiveXObject('Microsoft.XMLHTTP');   
   }     
 /*    1.缓存 在url?后面连接一个随机数,时间戳   
      2.乱码 编码encodeURI      */   
   xhr.open('get','2.get.php?username='+
encodeURI('刘伟')+'&age=30&' + new Date().getTime(),true);    
  xhr.send();    
        xhr.onreadystatechange = function() {       
           if ( xhr.readyState == 4 ) {    
        if ( xhr.status == 200 ) {    
           alert( xhr.responseText );  
          } else {       
        alert('出错了,Err:' + xhr.status);    
        }   
      }        
       }       
  }
}</script>
</head>
<body>  
 <input type="button" value="按钮" id="btn" />
</body>
</html>

post 方法
1)post方法必须设置请求头:xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');申明发送的数据类型, 否则后台无法获取前台传递的参数。
2)post方法没有缓存问题,也不需编码。

oBtn.onclick = function() {  
    var xhr = null;   
try {  
    xhr = new XMLHttpRequest();  
 } catch (e) {   
   xhr = new ActiveXObject('Microsoft.XMLHTTP');  
 }      xhr.open('post','2.post.php',true); 
  //post方式,数据放在send()里面作为参数传递  
 xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
  xhr.send('username=刘伟&age=30');    
  xhr.onreadystatechange = function() {      
      if ( xhr.readyState == 4 ) {   
      if ( xhr.status == 200 ) {     
       alert( xhr.responseText );   
      } else {        
    alert('出错了,Err:' + xhr.status);  
       }   
   }     
    } 
  }

另外:get方法是的参数暴露在url中,存在安全问题,而且只能够发送字符串类型的参数;get方法传输数据有数据量的限制,每种浏览器的限制都不相同。
post方法不仅能够发送字符串类型的数据,而且能够发送二进制等其他类型的数据,由于其发送的数据放在请求头里面,相比较get方法而言,相对安全。开发中应该根据实际情况选择到底使用哪一种方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容