Created
July 27, 2017 06:18
-
-
Save EsanLe/dab5a0698723aa1ed4a486b6117b311a to your computer and use it in GitHub Desktop.
jsonp.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file jsonp请求 | |
*/ | |
// 获取jsonp | |
const jsonp = (options) => { | |
if(!options || !options.url) return; | |
// const container = document.getElementsByTagName('body')[0]; | |
const container = document.body; | |
let scriptNode = document.createElement('script'); | |
let data = options.data || {}; | |
let url = options.url; | |
const callbackSuccess = options.callback[0]; | |
const callbackFail = options.callback[1]; | |
const timestamp = Date.parse(new Date()); | |
const fnName = "jsonp" + timestamp; | |
data["callback"] = fnName; | |
// 拼接url | |
let params = []; | |
for (var key in data) { | |
params.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key])); | |
} | |
url = url.indexOf("?") > 0 ? (url + "&") : (url + "?"); | |
url += params.join("&"); | |
scriptNode.src = url; | |
// 传递的是一个匿名的回调函数,要执行的话,暴露为一个全局方法 | |
global[fnName] = function (ret) { | |
callbackSuccess && callbackSuccess(ret); | |
container.removeChild(scriptNode); | |
delete global[fnName]; | |
} | |
// 出错处理 | |
scriptNode.onerror = function () { | |
callbackFail && callbackFail({error:"error"}); | |
container.removeChild(scriptNode); | |
global[fnName] && delete global[fnName]; | |
} | |
scriptNode.type = "text/javascript"; | |
container.appendChild(scriptNode) | |
}; | |
export default { | |
jsonp | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment