原生js ajax封装post,get方法
方法一:
function ajax(method, url, callback, data, flag) {
var xhr;
flag = flag || true;
method = method.toUpperCase();
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(2)
callback(xhr.responseText);
}
}
if (method == 'GET') {
var date = new Date(),
timer = date.getTime();
xhr.open('GET', url + '?' + data + '&timer' + timer, flag);
xhr.send()
} else if (method == 'POST') {
xhr.open('POST', url, flag);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(data);
}
}
方法二:
function serialize(data){//对发送数据的序列化
if(!data) return '';
var pairs=[];
for(var name in data){
if(!data.hasOwnProperty(name)) continue;//排除嵌套对象
if(typeof data[name]==='function') continue;//排除操作数是函数
var value=data[name].toString();
//encodeURIComponent对同一资源表示符(URI)编码,
name=encodeURIComponent(name);
valeu=encodeURIComponent(value);
pairs.push(name+'='+value);
}
return pairs.join('&');
}
//get方法封装
function get(url,options,callback){
if(window.XMLHttpRequest){
var xhr=new XMLHttpRequest();
}else if(window.ActiveXobject){//兼容IE7及以前版本
var xhr=new ActiveXobject('Microft.XMLHttp');
}
xhr.onreadystatechange=function(callback){
if(xhr.readyState==4){//请求结束时,readyState状态为4
if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
callback(xhr.responseText);
}else{
console.log('连接失败:'+xhr.status);
}
}
}
// http://localhost:8000/information?name=zhou&age=18
url=url+'?'+serialize(options);
xhr.open('get',url,true);//开启请求,readyState状态为1
xhr.send(null);//正式像服务器发送请求,readyState状态为2
}
//post方法封装
function post(url,options,callback){
if(window.XMLHttpRequest){
var xhr=new XMLHttpRequest();
}else if(window.ActiveXobject){//兼容IE7及以前版本
var xhr=new ActiveXobject('Microft.XMLHttp');
}
xhr.onreadystatechange=function(callback){
if(xhr.readyState==4){//请求结束时,readyState状态为4
if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
callback(xhr.responseText);
}else{
console.log('POST请求连接失败:'+xhr.status);
}
}
}
xhr.open('post',url,true);//开启请求,readyState状态为1
xhr.send(serialize(options));//正式像服务器发送请求,readyState状态为2
}
post('/information',{name:'zhou',age:18},function(data){
console.log(data);
});
get('/information',{name:'zhou',age:18},function(data){
console.log(data);
});
异步加载javascript:
function loadScript(url, callback) {
var oscript = document.createElement('script');
if (oscript.readyState) { // ie8及以下版本
oscript.onreadystatechange = function () {
if (oscript.readyState === 'complete' || oscript.readyState === 'loaded') {
callback();
}
}
} else {
oscript.onload = function () {
callback()
};
}
oscript.src = url;
document.body.appendChild(oscript);
}
还没有评论,来说两句吧...