原生js实现ajax请求
var Ajax = {
//在原生js中使用XMLHttpRequest对象实现
get:function(url,fn){
var xhr = new XMLHttpRequest();
//.open(method,url,async)
xhr.open(‘get’,url,true);
xhr.onreadystatechange = function(){
if(xhr.readyState = 4 && xhr.status == 200 || xhr.status == 304)
{
//获取请求到的数据
fn.call(this,xhr.responseText);
}
},
xhr.send();
},
post:function(url,data,fn){
var xhr = new XMLHttpRequest();
xhr.open(‘post’,url,true){
//post类型请求需要添加请求头!
xhr.setRequestHeader(‘content-type’,’application/x-www-form-urlencoded’);
//还是判断请求的状态
xhr.onreadystateChange=function(){
If(xhr.readystate ==4 && xhr.status ==200 || xhr.status ==304){
//注意状态信息和状态码,304表示协商缓存,与状态码301/302重定向无关
fn.call(this,xhr.responseText);
}
};
xhr.send(data);
}
}
$.Ajax
//有两个参数contentType与processData
contentType:默认值为”application/x-www-form-urlenvode”代表的是提交数据的编码类型,设置为false时代表自动检测;
processData默认值为true,为搭配contentType默认的编码类型,processData都会将data提交的参数数据转换为一个查询字符串,设置为false时则不转换为查询字符串,即可以传递DOM树信息或其他不希望转换的信息(比如提交的数据data中包含文件)