jsonp.js 1.67 KB
var Promise = require('./promise');

// jsonp请求
function jsonp(params) {
    return new Promise(function (resovle, reject) {
        params = params || {};
        params.data = params.data || {};
        //创建script标签并加入到页面中

        var callbackName = params.jsonp;

        if (window[callbackName]) {
            callbackName += Math.floor(Math.random() * 1000);
            params.jsonp = callbackName;
        }

        // 设置传递给后台的回调参数名
        params.data['callback'] = callbackName;
        var data = formatParams(params.data);
        var script = document.createElement('script');
        document.body.appendChild(script);

        // 创建jsonp回调函数
        window[callbackName] = function (json) {
            document.body.removeChild(script);
            clearTimeout(script.timer);
            window[callbackName] = null;
            return resovle(json);
        };

        // 发送请求
        script.src = params.url + '?' + data;

        //为了得知此次请求是否成功,设置超时处理
        if (params.timeout) {
            script.timer = setTimeout(function () {
                window[callbackName] = null;
                document.body.removeChild(script);
                reject({message: '超时'});
            }, params.timeout);
        }
    })
}

//格式化参数
function formatParams(data) {
    var arr = [];
    for (var name in data) {
        arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
    }

    // 添加一个随机数,防止缓存
    var date = new Date();
    arr.push('v=' + date.getTime());
    return arr.join('&');
}

module.exports = jsonp;