Node+H5 實現簡單的 JSONP 封裝

來源:互聯網
上載者:User

標籤:function   string   實現   blog   asc   函數   pre   封裝   返回   

前端代碼

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>JSONP</title></head><body></body><script type="text/javascript">    /* 封裝一個 JSONP 的 互動類 */    var JSONP = (function () {        /**         * @param url => 訪問的地址         * @param cbKey => 回呼函數的名稱, 服務端接收的欄位         * @param json => 傳給背景資料, 一個單層的 json 對象         * @param callBack => 回呼函數         */        var $ = {};        $.GetJson = function (url, cbKey, json, callBack) {            /* 擷取一個不會重複的 JSONP 回調名稱, 並將該名稱注入到類中實現一個方法 */            var cbValue = "json" + Math.random().toString(16).substr(2);            $[cbValue] = function (res, id) {                var domObj = document.getElementById(id.split(".")[1]).remove(0);                callBack(res);            };            /* 拼接請求地址 */            url = url + "?" + cbKey + "=JsonP." + cbValue;            for (var key in json) {                url += "&" + key + "=" + json[key];            }            /* 拼接 script 標籤 並寫入文檔對象 */            var script = ‘<script id="‘+ cbValue +‘" src="‘+ url +‘"><\/script>‘;            document.write(script);        };        return $;    })();    /* 調用 JSONP 互動類的方法 */    JSONP.GetJson("http://localhost/JsonP/Index", "cb", {id: 1}, function (res) {        console.log(res);    });</script></html>

後端代碼  => 基於 KOA 架構

// 引入外部依賴let Router = require("koa-router");// 執行個體化一個子路由let router = new Router();// 這裡寫商務邏輯router.get("/Index", async (ctx) => {    // 接收前端傳過來的回調方法    let callback = ctx.query.cb;    // 一番商務邏輯之後的傳回值    let result = {        id: ctx.query.id,    };    ctx.type = "text/javascript"; // 設定輸出為 JavaScript 檔案    /**     * 返回給前端的資料格式     * 前端傳遞的回調方法名( 返回給前端的資料格式, 前端傳遞的回調方法名 )     * 如: cb( {id: 1}, cb )     */    ctx.body = `${callback}(${JSON.stringify(result)}, "${callback}")`;});// 對外暴露模組module.exports = router;

 

 

 

 

 

Node+H5 實現簡單的 JSONP 封裝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.