• 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'
        }
    }
  • 相关阅读:
    PHP数组操作,数组排序,数组元素操作,数组元素定位
    提高PHP编程效率的53个要点
    javascript的一些简单的应用
    数字时钟
    一个限定变量范围的小技巧
    windows编程学习——1 关闭窗口不退出
    比木马NB多了
    模拟时钟
    恶搞程序——黑屏
    用白色画笔再画一遍,代替擦除
  • 原文地址:https://www.cnblogs.com/yhquan/p/11118716.html
Copyright © 2020-2023  润新知