Created
July 17, 2017 10:01
-
-
Save ryanzhouff/63efd6e0a41462b844f75c9a99a057da to your computer and use it in GitHub Desktop.
JSONP解决跨域问题
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
/** | |
Created: 2017年7月17日 18:00:41 | |
*/ | |
var responseHandler ; | |
function JSONP(url, callback) { | |
if (url === "" || url === undefined) return; | |
if (url.indexOf("?") === -1) { | |
url += "?callback=responseHandler" | |
} else { | |
url += "&callback=responseHandler" | |
} | |
var script = document.createElement("script"); | |
var head = document.getElementsByTagName("head")[0]; | |
responseHandler = function (json) { | |
try { | |
callback(json); | |
} catch (error) { | |
throw new Error(error); | |
} finally { | |
// 函数调用之后不管发生什么都要移除对应的标签 | |
script.parentNode.removeChild(script); | |
} | |
}; | |
console.log(url); | |
script.setAttribute("type", "text/javascript"); | |
script.setAttribute("src", url); | |
head.appendChild(script); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
调用方式: