want to know that when using jsonp to implement cross-domain, return data on the server side and put the data as parameters in the callback function
`callback(JSON.stringify(data))`
but at this time, the server should return a string, how does the browser directly execute the returned string as js code?
the complete code is as follows
// js
function jsonp (url) {
// script
var script = document.createElement("script")
script.src = url
script.id = "jsonp"
document.getElementsByTagName("body")[0].appendChild(script)
//
script.onload = () => {
document.getElementsByTagName("body")[0].removeChild(script)
script = null
}
}
function sendHaha (msg) {
console.log(msg)
}
jsonp("http://localhost:3333/haha?callback=sendHaha")
//
var http = require("http")
var urllib = require("url")
var data = {
data: "hhh"
}
http.createServer((req, res) => {
var params = urllib.parse(req.url, true)
var callback = params.query.callback
if (callback) {
var str = `${callback}(${JSON.stringify(data)})`
res.end(str)
}
}).listen(3333, () => {
console.log("haha")
})
Thank you for your answer ~ ~ Thank you very much