PHP實現(xiàn)跨域的幾種形式
1、JSONP(JSON with padding)原理
利用html里面script標(biāo)簽可以加載其他域下的js這一特性,使用script src的形式來獲取其他域下的數(shù)據(jù),但是,因為是通過標(biāo)簽引入的,
所以,會將請求到的JSON格式的數(shù)據(jù)作為js去運行處理,顯然這樣運行是不行的。
因此,就需要提前將返回的數(shù)據(jù)包裝一下,封裝成函數(shù)進(jìn)行運行處理,函數(shù)名通過接口傳參的方式傳給后臺,后臺解析到函數(shù)名后在原始
數(shù)據(jù)上包裹這個函數(shù)名,發(fā)送給前端。(JSONP 需要對應(yīng)接口的后端的配合才能實現(xiàn))
實例:
<script>function showData(ret){ console.log(ret); }</script><script src="http://api.jirengu.com/weather.php?callback=showData"></script>
當(dāng)script src請求到達(dá)后端后,后端會去解析callback這個參數(shù),獲取到字符串showData,在發(fā)送數(shù)據(jù)后端返回數(shù)據(jù),用showData封裝
一下,即showData({"json數(shù)據(jù)"}) ,前端script標(biāo)簽在加載數(shù)據(jù)后,會把json數(shù)據(jù)作為showData的參數(shù),調(diào)用函數(shù)運行。
2、CORS
CORS全稱是跨域資源共享(Cross-Origin Resource Sharing
),是一種 ajax 跨域請求資源的方式,支持現(xiàn)代瀏覽器,IE支持10以上。
實現(xiàn)方式:
當(dāng)使用XMLHttpRequest
發(fā)送請求時,瀏覽器發(fā)現(xiàn)該請求不符合同源策略,會給該請求加一個請求頭:Origin
,后臺進(jìn)行一系列處理,如果
確定接受請求,則在返回結(jié)果中加入一個響應(yīng)頭:Access-Control-Allow-Origin
;瀏覽器判斷該相應(yīng)頭中,是否包含Origin的值,如果
有,則瀏覽器會處理響應(yīng),我們就可以拿到響應(yīng)數(shù)據(jù),如果不包含,瀏覽器直接駁回,這時,我們無法拿到響應(yīng)數(shù)據(jù)。
實例:
server.js
var http = require('http') var fs = require('fs') var path = require('path') var url = require('url')http.createServer(function(req, res){ var pathObj = url.parse(req.url, true) switch (pathObj.pathname) { case '/getNews': var news = [ "第11日前瞻:中國沖擊4金 博爾特再戰(zhàn)200米羽球", "正直播柴飚/洪煒出戰(zhàn) 男雙力爭會師決賽", "女排將死磕巴西!郎平安排男陪練模仿對方核心" ] res.setHeader('Access-Control-Allow-Origin','http://localhost:8080') //res.setHeader('Access-Control-Allow-Origin','*') res.end(JSON.stringify(news)) break; default: fs.readFile(path.join(__dirname, pathObj.pathname), function(e, data){ if(e){ res.writeHead(404, 'not found') res.end('<h1>404 Not Found</h1>') }else{ res.end(data) } }) }}).listen(8080)
index.html
<!DOCTYPE html><html><body> <div class="container"> <ul class="news"></ul> <button class="show">show news</button> </div><script> $('.show').addEventListener('click', function(){ var xhr = new XMLHttpRequest() xhr.open('GET', 'http://127.0.0.1:8080/getNews', true) xhr.send() xhr.onload = function(){ appendHtml(JSON.parse(xhr.responseText)) } }) function appendHtml(news){ var html = '' for( var i=0; i<news.length; i++){ html += '<li>' + news[i] + '</li>' } $('.news').innerHTML = html } function $(selector){ return document.querySelector(selector) } </script> </html>
3、postMessage
假設(shè)有兩個域名(主域域名不一致),其中iframe頁面是允許訪問調(diào)用,那么就可以用postMessage實現(xiàn)。
原理:a域名發(fā)送請求postMessage,b域名間聽到了message事件,就處理并返回數(shù)據(jù)
//b域名<script>window.frames[0].postMessage(this.value, '*'); //*號表示在任何域下都可以接收message window.addEventListener('message', function(e){ console.log(e.data); });</script>
以上內(nèi)容僅供參考!
推薦教程:PHP視頻教程