• jsonp


    import { NetWorkError } from '../common/errors.js'
    
    let jsonpId = 1;
    export function jsonpCallbackId() {
        return jsonpId ++;
    }
    
    export function jsonpRequest(url, params) {
        let pStr;
        let reqUrl = url + '?' + '_=' + Date.now() + ((pStr = param2String(params)) ? '&' + pStr : '');
        return sendJsonp(reqUrl);
    }
    
    // 将键数据转换成get请求的参数形式
    function param2String(params) {
        if (typeof params === 'string') {
            return params;
        }
        return objectToParamString(params);
    }
    
    // 将对象转换成键值对形式,只支持单层
    function objectToParamString(params) {
        let ret = '';
        for (let key in params) {
            ret = ret + key + '=' + encodeURIComponent(params[key]) + '&';
        }
        ret = ret.substr(0, ret.length-1); // 去除最后的'&'
        return ret;
    }
    
    function sendJsonp(reqUrl) {
        return new Promise((resolve, reject)=>{
            let callbackName = 'jsonp_cb_' + jsonpCallbackId();
            let script = document.createElement('script');
            let respData = null;
            let isTimeout = false;
    
            let timeout = setTimeout(()=>{
                isTimeout = true;
                reject(new NetWorkError('timeout'));
            }, 5000);
    
            let loadCallback = ()=>{
                clearTimeout(timeout);
                if(!isTimeout) {
                    respData ? resolve(respData) : reject(new NetWorkError('error'));
                }
                delete window[callbackName];
                script.removeEventListener('load', loadCallback);
                script.removeEventListener('error', loadCallback);
                document.head.removeChild(script);
            }
    
            script.addEventListener('load',loadCallback);
            script.addEventListener('error', loadCallback);
        
            window[callbackName] = function(resp){
                respData = resp;
            }
    
            script.src = reqUrl + '&callback=' + callbackName;
            document.head.appendChild(script);
        });
    }

    errors.js

    export class NetWorkError extends Error {
        constructor(message) {
            super(message)
        
            this.errorType = 'NetWorkError'
        }
    }
  • 相关阅读:
    1137. 第 N 个泰波那契数
    486. 预测赢家
    python函数—函数的参数+递归函数
    python函数—调用函数+定义函数
    Seize the day
    数学建模基础学习2-matlab + lingo
    Python基础--使用list和tuple+条件判断+使用dict和set
    经济学人精读丨中国的电子商务
    数学建模基础学习1
    C盘今天爆掉了,罪魁祸首--百度云管家
  • 原文地址:https://www.cnblogs.com/yhquan/p/11118716.html
Copyright © 2020-2023  润新知