想知道,在利用jsonp實(shí)現(xiàn)跨域的時(shí)候,在服務(wù)端返回?cái)?shù)據(jù),把數(shù)據(jù)作為參數(shù)放到回調(diào)函數(shù)中`callback(JSON.stringify(data))`但是此時(shí)服務(wù)端返回的應(yīng)該是個(gè)字符串呀,瀏覽器是如何直接把這個(gè)返回的字符串當(dāng)成js代碼執(zhí)行的?完整代碼如下//jsfunctionjsonp(url){//創(chuàng)建script標(biāo)簽varscript=document.createElement('script')script.src=urlscript.id='jsonp'document.getElementsByTagName('body')[0].appendChild(script)//移除標(biāo)簽,清除占用內(nèi)存script.onload=()=>{document.getElementsByTagName('body')[0].removeChild(script)script=null}}functionsendHaha(msg){console.log(msg)}jsonp('http://localhost:3333/haha?callback=sendHaha')//服務(wù)端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')})謝謝大佬的解答~~感激不盡
關(guān)于 jsonp 的一些疑問(wèn)
皈依舞
2019-05-12 09:14:58