本文已参与「新人创作礼」活动,一起开启掘金创作之路
- get和post一起封装
function ajaxpro(option){
var aja=new XMLHttpRequest();
if (option.type=='get'&&option.data){
option.url=option.url+'?'+option.data;
option.data=null;
};
aja.open(option.type,option.url);
if (option.type=='post'&&option.data){
aja.setRequestHeader('Content-type','application/x-www-form-urlencoded');
};
aja.onreadystatechange=function () {
if(aja.readyState==4&&aja.status==200){
type=aja.getResponseHeader('Content-Type');
if (type.indexOf('xml')!=-1){
option.success(aja.responseXML);
}else if(type.indexOf('json')!=-1){
option.success(aja.responseText);
}else {
option.success(aja.responseText);
}
}
};
aja.send(option.data);
};
- get方式
function get(url,data,success) {
var getdat=new XMLHttpRequest();
if(url){
url+='?'+data;
};
getdat.open('get',url);
getdat.onreadystatechange=function () {
if (getdat.readyState==4&&getdat.status==200){
success(getdat.responseText);
}
};
getdat.send(null);
};
- post方式
function post(url,data,success){
var postdat=new XMLHttpRequest();
postdat.open('post',url);
if(url){
postdat.setRequestHeader('content-type:application/x-www-urlencoded');
};
postdat.onreadystatechange=function () {
if (postdat.readyState==4&&getdat.status==200){
success(postdat.responseText);
}
};
postdat.send(null);
};