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' } }