//修改了一个bug,增加了手动释放垃圾
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>jsonp跨域源码插件封装</title> </head> <body> <input type="text" id="code"> <input type="button" value="查询" id="serch"> <script> ; (function (win) { const jsonp = function (dataPack) { const callback = dataPack.callBack || ''; const code = dataPack.code || 'sh000001'; const getUrl = 'http://hq.sinajs.cn/list=' + code; let scriPt = document.createElement('script'); scriPt.src = getUrl; scriPt.id = 'xl'; const oldScript = document.getElementById('xl'); const success = function () { const val = eval('hq_str_' + code); //手动垃圾回收 for (let i in window) { if (/^hq_str_/.test(i)) { window[i] = null; } } callback && callback(val); } const error = function () { callback && callback('跨域发生了错误!'); } if (oldScript) { document.body.removeChild(oldScript); document.body.appendChild(scriPt); } else { document.body.appendChild(scriPt); } scriPt.onload = success; scriPt.onerror = error; } win.jsonp = jsonp; })(window); document.querySelector('#serch').addEventListener('click', function () { jsonp({ code: document.querySelector('#code').value, callBack: function (data) { console.log(data); } }); }) </script> </body> </html>