前端修炼JS篇 -- ajax&&jsonp

原创
2017/07/20 15:23
阅读数 62

ajax

//url, data, type, time, success, error
function ajax(options) {
    options = options || {};
    options.data = options.data || {};
    options.type = options.type || 'get';
    options.time = options.time || 0;

    //把data拼起来
    var arr = [];

    for (var name in options.data) {
        arr.push(name + '=' + encodeURIComponent(options.data[name]));
    }
    var sData = arr.join('&');

    //创建
    if (window.XMLHttpRequest) {
        var oAjax = new XMLHttpRequest();
    } else {
        var oAjax = new ActiveXObject('Microsoft.XMLHttp');
    }

    //连接
    //发送

    if (options.type == 'get') {
        oAjax.open('get', options.url + '?' + sData, true);
        oAjax.send();
    } else {
        oAjax.open('post', options.url, true);
        oAjax.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
        oAjax.send(sData);
    }

    //接收
    oAjax.onreadystatechange = function () {
        if (oAjax.readyState == 4) {
            if (
                (oAjax.status >= 200 && oAjax.status < 300) ||
                oAjax.status == 304
            ) {
                options.success && options.success(oAjax.responseText);
            } else {
                options.error && options.error();
            }
        }
    };

    if (options.time) {
        setTimeout(function () {
            oAjax.abort();
        }, options.time);
    }
}


jsonp

//url,data,success,error,cbKey,timeout

function jsonp(options) {

    //整理options
    options = options || {};
    if (!options.url) return;
    options.data = options.data || {};
    options.success = options.success || null;
    options.error = options.error || null;
    options.cbKey = options.cbKey || 'cb';
    options.timeout = options.timeout || 0;


    //data少一个回调		{wd:xxx}
    var cbValue = 'jsonp' + Math.random();//函数名随机

    options.data[options.cbKey] = cbValue.replace('.', '');

    //在外面做个全局的show,将来会被调用
    window[options.data[options.cbKey]] = function (json) {

        clearInterval(timer);

        options.success && options.success(json);
        //删除script标签
        document.getElementsByTagName('head')[0].removeChild(oScript);
        window[options.data[options.cbKey]] = null;
    };

    var arr = [];
    for (var key in options.data) {
        arr.push(key + '=' + encodeURIComponent(options.data[key]));
    }

    options.url = options.url + '?' + arr.join('&')//wd=xunlei&cb=show

    var oScript = document.createElement('script');
    oScript.src = options.url;
    document.getElementsByTagName('head')[0].appendChild(oScript);

    if (options.timeout) {
        var timer = setTimeout(function () {
            options.error && options.error();
            window[options.data[options.cbKey]] = function () {/*dddd*/
            };
        }, options.timeout);
    }
}

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部