1.实现原理流程
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210209112312357.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTk2MzQ0MA==,size_16,color_FFFFFF,t_70)
2.源码
<body>
<script>
function getJSONP(url, callback) {
if (!url) {
return;
}
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var r1 = Math.floor(Math.random() * 10);
var r2 = Math.floor(Math.random() * 10);
var r3 = Math.floor(Math.random() * 10);
var name = 'getJSONP' + a[r1] + a[r2] + a[r3];
var cbname = 'getJSONP.' + name;
if (url.indexOf('?') === -1) {
url += '?jsonp=' + cbname;
} else {
url += '&jsonp=' + cbname;
}
console.log(url);
var script = document.createElement('script');
getJSONP[name] = function(data){
try{
callback && callback(data);
}catch(e){
}finally{
delete getJSONP[name];
script.parentNode.removeChild(script);
}
}
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
getJSONP('http://class.imooc.com/api/jsonp', function (response) {
console.log(response);
});
</script>
</body>