標籤: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 封裝