原生javascript封装类似jquery的ajax请求跨域函数

在网上查看了很多js封装的ajax函数,发现大部分都没有实现跨域请求

跨域请求浏览器就会提示:No 'Access-Control-Allow-Origin' header is present on the requested resource.

封装类似于JQuery的ajax函数:

js代码:

function ajax(obj) {
    // 对实参处理
    obj = obj || {};
    // 定义局部变量
    var xmlhttp, type, url, async, dataType, data;
    // 默认type为GET
    type = obj.type || 'GET';
    type = trim(type).toUpperCase();
    // 接口
    url = obj.url
    url = trim(url);
    // 默认为异步请求
    async = obj.async || true;
    // 设置跨域
    dataType = obj.dataType || 'HTML';
    dataType = trim(dataType).toUpperCase();
    // 发送参数
    data = obj.data || {};
    // 删除左右空格
    function trim(str) {
        return str.replace(/^\s+|\s+$/g, "");
    };
    // 定义格式化参数函数
    var formatParams = function() {
            if (typeof(data) == "object") {
                var str = "";
                for (var pro in data) {
                    str += pro + "=" + data[pro] + "&";
                }
                data = str.substr(0, str.length - 1);
            }
            if (type == 'GET' || dataType == 'JSONP') {
                if (url.lastIndexOf('?') == -1) {
                    url += '?' + data;
                } else {
                    url += '&' + data;
                }
            }
        }
    // 第一步,创建xmlhttprequest对象用来和服务器交换数据。
    if (window.XMLHttpRequest) {
        //Chrome || Firefox
        xmlhttp = new XMLHttpRequest();
    } else {
        //IE
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    // 跨域请求
    if (dataType == 'JSONP') {
        if (typeof(obj.beforeSend) == 'function') obj.beforeSend(xmlhttp);
        var callbackName = ('jsonp_' + Math.random()).replace(".", "");
        var oHead = document.getElementsByTagName('head')[0];
        data.callback = callbackName;
        var ele = document.createElement('script');
        ele.type = "text/javascript";
        ele.onerror = function() {
            console.log('failed');
            obj.error && obj.error("failed");
        };
        oHead.appendChild(ele);
        window[callbackName] = function(json) {
            oHead.removeChild(ele);
            window[callbackName] = null;
            obj.success && obj.success(json);
        };
        formatParams();
        ele.src = url;
        return;
    } else {
        formatParams();
        // 第二步,打开链接
        xmlhttp.open(type, url, async);
        // 设置响应头
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
        if (typeof(obj.beforeSend) == 'function') obj.beforeSend(xmlhttp);
        // 第三步,发送请求
        xmlhttp.send(data);
        // 第四步,响应处理
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.status != 200) {
                console.log(xmlhttp.status + 'failed');
                obj.error && obj.error(xmlhttp.status + 'failed');
                return;
            }
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                if (dataType == 'JSON') {
                    try {
                        res = JSON.parse(xmlhttp.responseText);
                    } catch (e) {
                        console.log('json格式错误');
                        obj.error('json格式错误');
                    }
                } else if (dataType == 'XML') {
                    res = xmlhttp.responseXML;
                } else {
                    res = xmlhttp.responseText;
                }
                obj.success && obj.success(res);
            }
        }
    }
}

使用示例:

 

ajax({
     url: 'http://open.iciba.com/dsapi',
     type: "get",
     dataType: "jsonp",
     success: function(data) {
     	console.log(data);
     },
     error: function(err) {
     	console.log(err);
     }
 })

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值