超簡(jiǎn)單的實(shí)現(xiàn)一個(gè)jsonp庫

需求

在調(diào)用QQ音樂搜索歌曲api的時(shí)候發(fā)現(xiàn)返回是一個(gè)jsonp

請(qǐng)求url:
https://c.y.qq.com/splcloud/fcgi-bin/smartbox_new.fcg?format=jsonp&key=周杰倫&jsonpCallback=call&format=jsonp
返回:call({xxx})


call是根據(jù)我們傳遞的jsonpCallback的值決定的

實(shí)現(xiàn)

我希望有一個(gè)jsonp對(duì)象,可以這樣使用

new Jsonp({
  url: 'http://xxxx',
  callBackname: 'call',
  success: function(result){
    //處理數(shù)據(jù)
  }
});
完整代碼
//基本結(jié)構(gòu)
!(function(window){
  function Json(param){
   //初始化參數(shù)
       let ele = document,
       script = ele.createElement('script'),
       result = null,
       _url = param.url || '',
       _success = param.success || function () { },
       _error = param.error || function () { };
                
        if( !param.callbackName ){ throw new Error('callbackName is required!');}
        window[param.callbackName] = function(){ result = arguments[0]; };

        ele.getElementsByTagName('head')[0].appendChild(script);

       script.onload = script.readystatechange = function () {
           if (!script.readyState || /loaded|complete/.test(script.readyState)) {
               _success(result);
               script.onload = script.readystatechange = null;
               }else{
                   _error();
              }
      }         
     script.src = _url;
  }
  window.Jsonp = Jsonp;
})(window);
測(cè)試(調(diào)用QQ音樂搜索API)
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        *{margin: 0;padding: 0}
        table{
            width: 100%;
            text-align: center;
            border-spacing: none;
            border-collapse: collapse;
            border: 1px solid #eee;
            line-height: 45px;
        }
        .container{
            width: 500px;
            margin: 100px auto;
        }
        td,th{
            border: 1px solid #eee;
        }
        input{
            margin-top: 10px;
            width: 100%;
            height: 35px;
            line-height: 35px;
            border: 1px solid #eee;
            outline: none;
            text-indent: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <table>
            <thead>
                <caption>QQ音樂搜索API調(diào)用</caption>
                <tr>
                    <th>id</th>
                    <th>name</th>
                    <th>singer</th>
                </tr>
            </thead>
            <tbody id="result">
                
            </tbody>
        </table>
        <div>
            <input id="key" type="text" placeholder="歌曲或者歌手...">
        </div>
    </div>
    
    <script>
        !(function (window) {

            function Jsonp(param) {
                let ele = document,
                    script = ele.createElement('script'),
                    result = null,
                    _url = param.url || '',
                    _success = param.success || function () { },
                    _error = param.error || function () { };
                
                if( !param.callbackName ){ throw new Error('callbackName is required!'); }

                window[param.callbackName] = function(){ result = arguments[0]; };

                ele.getElementsByTagName('head')[0].appendChild(script);

                script.onload = script.readystatechange = function () {
                    if (!script.readyState || /loaded|complete/.test(script.readyState)) {
                        _success(result);
                        script.onload = script.readystatechange = null;
                    }else{
                        _error();
                    }
                }
                
                script.src = _url;
            }

            window.Jsonp = Jsonp;

        })(window);

        document.getElementById('key').addEventListener('keyup',function(){
            let key = document.getElementById('key').value;
            new Jsonp({
                url: `https://c.y.qq.com/splcloud/fcgi-bin/smartbox_new.fcg?format=jsonp&key=${key}&jsonpCallback=call&format=jsonp`,
                callbackName: 'call',
                success: function (result) {
                    if (result) {
                        render(result);
                    }
                },
                error: function(){
                    console.log('error');
                }
            });
        },false);

        

        function render(result){
            console.log(result);
            let dom = document.getElementById('result');
            let tmp = '';
            
            result.data.song.itemlist.forEach(ele => {
                tmp += `<tr><td>${ele.id}</td><td>${ele.name}</td><td>${ele.singer}</td></tr>`;
            });
            dom.innerHTML = tmp;
        }
    </script>
</body>
</html>
思路

1.初始化參數(shù)
2.綁定call事件(服務(wù)器返回的函數(shù)調(diào)用)來獲取返回值
3.動(dòng)態(tài)創(chuàng)建script標(biāo)簽
4.script加載完成后進(jìn)行回調(diào)success并把返回值傳遞出去
5.加載失敗則回到error

本人小白一枚,代碼很爛,沒有處理請(qǐng)求參數(shù),/捂臉 打包了在github
https://github.com/TankCJZ/JsonpDemo

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評(píng)論 19 139
  • Lua 5.1 參考手冊(cè) by Roberto Ierusalimschy, Luiz Henrique de F...
    蘇黎九歌閱讀 14,246評(píng)論 0 38
  • 消費(fèi)人群定位
    Monique7閱讀 170評(píng)論 0 0
  • 花開兩朵,各表一枝。我言天方,君說咫尺,折翅飛翔,幽在夢(mèng)想。時(shí)與空合,謂為宇宙,恐在其中,不知所謂。
    秋落鳴蟬閱讀 104評(píng)論 0 1
  • 詞匯 the press and public were atwitter, anticipating that'...
    谷音sp閱讀 405評(píng)論 0 0

友情鏈接更多精彩內(nèi)容