index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <button id="btn1">请求</button> <!-- <script> function test(data) { alert(data.name); } </script> <script src="http://127.0.0.1:8080/jsonp?callback=test"></script> --> <script> function addScriptTag(src) { var script = document.createElement("script"); script.setAttribute(‘type‘, ‘text/javascript‘); script.src = src; document.body.appendChild(script); } var oBtn = document.querySelector("#btn1"); oBtn.onclick = function() { addScriptTag("http://127.0.0.1:8080/jsonp?callback=hello") }; function hello(data) { console.log(data); } </script> </body> </html>
server.js
var http = require(‘http‘); var url = require(‘url‘); var querystring = require(‘querystring‘); var server = http.createServer(); server.on(‘request‘, function (req, res) { var urlPath = url.parse(req.url).pathname; var qs = querystring.parse(req.url.split(‘?‘)[1]); // http://localhost:8080/jsonp?callback=test // { callback: ‘test‘ } if (urlPath === "/jsonp" && qs.callback) { res.writeHead(200, { ‘Content-Type‘: ‘text/plain;charset=utf-8‘ }); var data = { "name": "Monkey" }; data = JSON.stringify(data); var callback = qs.callback + ‘(‘ + data + ‘);‘; res.end(callback); } else { res.writeHead(200, { ‘Content-Type‘: ‘text/html;charset=utf-8‘ }); res.end(‘Hello World\n‘); } }); server.listen(‘8080‘);