Ajax的原生以及封装

//ajax调用函数

//url,data,type,timeout,success,error

function ajax(json){

json=json || {};

json.data=json.data || {};

json.type=json.type || 'get';

json.timeout=json.timeout || 0;

if(window.XMLHttpRequest){

var oAjax=new XMLHttpRequest();

}else{

var oAjax=new ActiveXObject('Microsoft.XMLHttp');

}

var arr=[];

for(var name in json.data){

arr.push(name+'='+encodeURIComponent(json.data[name]));

}

var sData=arr.join('&');

if(json.type=='post'){

oAjax.open('post',json.url,true);

oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

oAjax.send(sData);

}else{

oAjax.open('get',json.url+'?'+sData,true);

oAjax.send();

}

oAjax.onreadystatechange=function(){

if(oAjax.readyState==4){

clearTimeout(timer);

if((oAjax.status>=200 && oAjax.status<=300) || oAjax.status==304 ){

json.success && json.success(oAjax.responseText)

}else{

json.error && json.error(oAjax.status);

}

}

}

if(json.timeout){

var timer=setTimeout(function(){

oAjax.abort();

},json.timeout);

}

}

//ajax使用方法;

//var data='act=add&user='+AddT.value+'&pass='+AddPass.value;

//ajax({"url":"user.php","type":"get","data":{},success:function(str){},error:function(){}});

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.语言基础2.严格模式3.js组成(ECMAScript DOM BOM)4.各种(DOM BOM)例子5.组件...
    蒲公英_前端开发者阅读 1,558评论 0 3
  • ajax是什么: ajax简单的说就是做数据交互使用的。 Ajax的原理简单来说通过XmlHttpRequest对...
    liudai123阅读 421评论 0 0
  • 大家听过Ajax交互,可如何实现以及如何封装一个Ajax呢?今天就带大家来封装一个原生的Ajax; 喜欢请用你们的...
    BrightenSun阅读 180评论 0 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,860评论 18 139
  • 一些想法和注意 顶栏命令中,编辑是对图层形状区块进行操作,选择是对选区。每当想要在选区填充颜色的时候,查看是否是在...
    daorren阅读 1,539评论 0 6