node.js
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
var _callback = req.query.callback;
console.log(_callback)
var data = { data:'Hello World!' };
if (_callback) {
res.type('text/javascript');
res.send(_callback + '(' + JSON.stringify(data) + ')');
}
else {
res.json(data);
}
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
前端
function callbackFunction(result){
console.log(result)
}
function jsonP() {
let script = document.createElement('script')
script.src = 'http://localhost:3000?callback=callbackFunction'
let body = document.getElementsByTagName('body')[0]
body.appendChild(script)
}