Some questions about jsonp

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

Aug.10,2021

I don't understand why there is such a question.
Code originally written in script is automatically compiled and executed
usually js

//a.js
callback(123)

Page reference

<script>
   function callback(p){
        console.log(p)//123
    }
</script>

//a.js  :callback(123) 
<script src="a.js"></script>

you are now returning the contents of a.js with background control, just changing the layer

.
var script = document.createElement('script');
script.id = 'jsonp'
script.innerHTML = 'callback(123)'
document.getElementsByTagName('body')[0].appendChild(script)

${callback} (${JSON.stringify (data)}) to:

`${callback}({${JSON.stringify(data)}})`

I made a mistake just now. You don't have to.
you just need to deal with it in your callback method:

function sendHaha (msg) {
      var data = JSON.parse(msg);
    }
Menu