Front-end Code
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>JSONP</title></Head><Body></Body><Scripttype= "Text/javascript"> /*encapsulates an interaction class for a JSONP*/ varJSONP= (function () { /** * @param url = * Access address * @param cbkey = name of the callback function, field received by the server @param JSON = data passed to the background. A single-layered JSON object * @param callBack + = callback function*/ var $ = {}; $. Getjson= function(URL, Cbkey, JSON, CallBack) {/*gets a JSONP callback name that does not duplicate and injects that name into the class to implement a method*/ varCbvalue= "JSON" +math.random (). toString ( -). substr (2); $[cbvalue]= function(res, id) {varDomobj=document.getElementById (Id.split (".")[1]). Remove (0); CallBack (RES); }; /*Stitching Request Address*/URL=URL+ "?" +Cbkey+ "=jsonp." +Cbvalue; for (varKeyinchJSON) {URL+= "&" +Key+ "=" +Json[key]; } /*stitching script tags and writing to document objects*/ varScript= '<script id= "'+Cbvalue+'"src="'+URL+'"><\/script>'; document.write (script); }; return $; })(); /*methods for invoking JSONP interaction classes*/JSONP. Getjson ("Http://localhost/JsonP/Index", "CB", {ID:1}, function(res) {Console.log (res); });</Script></HTML>
Back-end code = = based on KOA framework
//Introducing external DependenciesLet Router = require ("Koa-router");//instantiate a sub-routeLet router =NewRouter ();//Write business logic hereRouter.get ("/index", async (CTX) = { //the callback method that the receiving front end passes overLet callback =CTX.QUERY.CB; //The return value after the business logicLet result ={id:ctx.query.id,}; Ctx.type= "Text/javascript";//set Output to JavaScript file /** * The data format returned to the front end * The callback method name passed by the front end (the data format returned to the front end, the callback method name passed by the front end) * such as: CB ({id:1}, CB)*/Ctx.body= ' ${callback} (${json.stringify (Result)}, "${callback}")`;});//External Exposure ModuleModule.exports = router;
Node+h5 for a simple JSONP package