AJAX的post和get
2019-05-17 本文已影响0人
Mr君
ajax步骤
- 创建XMLHttpRequest对象(异步调用对象).
- 创建一个新的HTTP请求,并指定该HTTP请求的方法、URL及验证信息.
- 设置响应HTTP请求状态变化的函数.
- 发送HTTP请求(send方法调用).
- 获取异步调用返回的数据.
post和get的区别
- GET请求会将参数跟在URL后进行传递,而POST请求则是作为HTTP消息的实体内容发送给WEB服务器。
- GET方式提交的数据最多只能是1024字节,Post传输的数据量大,可以达到2M。
- GET方式请求数据会被浏览器缓存起来,因此其他人就可以从浏览器的历史记录中读取到这些数据,例如账号密码等。在某种情况下,GET方式会带来严重的安全问题。而POST方式相对来说就可以避免这些问题。
- Post请求必须设置Content-Type值为application/x-form-www-urlencoded。
- 发送请求时,因为Get请求的参数都在url里,所以send函数发送的参数为null,即使传入参数也会被忽略,而Post请求在使用send方法时,却需赋予其参数。
-
GET参数值只能是数字和字符串,而POST除了可以传数字和字符串外,还可以传递二进制数据.
区别.png
代码
- post
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 );
}
- get
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 );
}