AJAX封装

建议把所有代码放在.js文件中:

function ajax(json){
    if(!json.url)return;
    json.data=json.data || {};
    json.type=json.type || 'get';
    json.time=json.time || '3000';
    
    var timer=null;
    //创建一个ajax对象
    if (window.XMLHttpRequest) {
        var oAjax=new XMLHttpRequest();
    } else{
        //兼容ie低版本
        var oAjax=new ActiveXObject('Microsoft.XMLHTTP');
    }
    switch(json.type.toLowerCase()){ //忽略大小写
        case 'get':
            oAjax.open('GET',json.url+'?'+str2Json(json.data),true);
            oAjax.send();
        break;
        case 'post':
            oAjax.open('POST',json.url,true);
            //设置一个请求头
            oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            oAjax.send(json2Str(json.data));
        break;
    }
    //监控状态
    oAjax.onreadystatechange=function(){
        if(oAjax.readyState==4)
        {
            if(oAjax.status>=200&&oAjax.status<300 ||oAjax.status==304){
                json.success && json.success(oAjax.responseText);
            }else{
                json.error && json.error(oAjax.status);
            }
            clearTimeout(timer);
        }
    };
    timer=setTimeout(function(){
        alert('服务器超时!')
        oAjax.onreadystatechange=null;
    },json.time);
};

//百度接口https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&cb=show
//处理接口?后边的如 :wd=a&cb=show
function json2Str(json){
    json.t=Math.random();//加随机数
    var arr=[];
    for(var name in json){
        arr.push(name+'='+json[name]);
    }
    return arr.join('&');
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 使用传字符串的形式 html页面代码: js代码: 使用对象的形式: html代码: js代码: ![Upload...
    清心挽风阅读 3,991评论 0 0
  • (1) ajax数据请求在项目中用到的频率会很高,所以对这些高频率组件进行封装,以便使用 r.detail的de...
    啥啥啥娜娜阅读 3,304评论 0 1
  • 1.新建一个html文件,在里面设置一个按钮,点击按钮就会获取test.txt里面的内容 2.编写实现代码 <!D...
    梦想秀阅读 1,488评论 0 0
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,354评论 25 709
  • https://developer.apple.com/support/技术支持 https://develope...
    MillerWang阅读 5,861评论 0 1