zoukankan      html  css  js  c++  java
  • jsonp原生js跨域拿新浪数据插件封装【可扩展】

    //修改了一个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>
    

      

  • 相关阅读:
    stm32的hal之串口库函数总结复习
    关闭win10 任务栏窗口预览的步骤:
    sizeof的注意点
    goto语句——慎用,但是可以用
    #define的一个小技巧
    Chapter 1 First Sight——36
    Chapter 1 First Sight——35
    Chapter 1 First Sight——34
    leetcode409
    Chapter 1 First Sight——34
  • 原文地址:https://www.cnblogs.com/webSong/p/9418828.html
Copyright © 2011-2022 走看看