想知道,在利用jsonp實現跨域的時候,在服務端返回數據,把數據作為參數放到回調函數中`callback(JSON.stringify(data))`但是此時服務端返回的應該是個字符串呀,瀏覽器是如何直接把這個返回的字符串當成js代碼執行的?完整代碼如下//jsfunctionjsonp(url){//創建script標簽varscript=document.createElement('script')script.src=urlscript.id='jsonp'document.getElementsByTagName('body')[0].appendChild(script)//移除標簽,清除占用內存script.onload=()=>{document.getElementsByTagName('body')[0].removeChild(script)script=null}}functionsendHaha(msg){console.log(msg)}jsonp('http://localhost:3333/haha?callback=sendHaha')//服務端varhttp=require('http')varurllib=require('url')vardata={data:'hhh'}http.createServer((req,res)=>{varparams=urllib.parse(req.url,true)varcallback=params.query.callbackif(callback){varstr=`${callback}(${JSON.stringify(data)})`res.end(str)}}).listen(3333,()=>{console.log('haha')})謝謝大佬的解答~~感激不盡
關于 jsonp 的一些疑問
皈依舞
2019-05-12 09:14:58