请求方式
我们常用的请求方式有get请求和post请求,其中get请求一般是用来获取数据的,post请求一般是上传数据的。
get请求
function get(url,callback) {
var xhr = new XMLHttpRequest()
xhr.open("GET",url,true); //get请求的参数一般在url的?后边,格式是?参数1=值&参数2=值
xhr.send();
xhr.onreadystatechange = function () {
if(xhr.readyState==4 && xhr.status == 200){
if(callback){
callback(xhr.responseText)
}
上面的if代码 也可以简写成逻辑运算符的短路操作
callback && callback(xhr.responseText)
}
}
}
post请求
function post(url,callback) {
var xhr = new XMLHttpRequest()
xhr.open("POST",url,true);
//post请求需要伪装成form请求
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(); //post需要上传的参数在send里,格式是参数1=值&参数2=值
xhr.onreadystatechange = function () {
if(xhr.readyState==4 && xhr.status == 200){
if(callback){
callback(xhr.responseText)
}
上面的if代码 也可以简写成逻辑运算符的短路操作
callback && callback(xhr.responseText)
}
}
}
get和post的区别
- 提交方式不同
xhr.open(“POST”,url,true);
xhr.open(“GET”,url,true); - 参数位置不同
GET
url之后的 ? + 参数1&参数2 //最多1024字节限制
POST
参数放在send中
send(“参数1&参数2”) - 使用POST请求需要设置请求头
xhr.setRequestHeader(“Content-Type”,“application/x-www-form-urlencoded”); - 安全程度不同
GET请求的数据会被缓存,其他人可以从浏览器历史记录读到数据,比如账号密码等,而POST请求不存在这种安全问题。
jquery中的ajax
jquery里已经有封装好的ajax,不需要我们再去写原生的ajax请求了,但是原生ajax的原理还是要了解的
$.ajax(
{
url:请求地址,//必填
data:{
发送的参数
}
dataType:"json", //请求返回的数据格式
beforeSend :function(){
请求发送前执行的函数,一般用来设置加载动画
},
success:function(data){ //请求成功时执行的函数
console.log(data) //返回的数据
},
complete:function(){
请求结束时执行的函数,一般用来取消加载动画
}
}
)
除了$.ajax还有其他已经封装好的方法
$.get(url,data,callback(),"json",......)
$.post(url,data,callback(),"json",......)
$.getJSON(url,data,callback(),"json",......) 这里边比get只少了type参数