JSONP(JSON with padding)
JSONP是通過 script 標(biāo)簽加載數(shù)據(jù)的方式去獲取數(shù)據(jù)當(dāng)做 JS 代碼來執(zhí)行 提前在頁面上聲明一個函數(shù),函數(shù)名通過接口傳參的方式傳給后臺,后臺解析到函數(shù)名后在原始數(shù)據(jù)上「包裹」這個函數(shù)名,發(fā)送給前端。換句話說,JSONP 需要對應(yīng)接口的后端的配合才能實現(xiàn)。
創(chuàng)建服務(wù)器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('Content-Type','text/json; charset=utf-8')
//后端支持jsonp
if(pathObj.query.callback){
res.end(pathObj.query.callback + '(' + JSON.stringify(news) + ')')
}else{
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 script = document.createElement('script');
script.src = 'http://127.0.0.1:8080/getNews?callback=appendHtml';
document.head.appendChild(script);
document.head.removeChild(script);
})
function appendHtml(news){
var html = '';
for( var i=0; i<news.length; i++){
html += '<li>' + news[i] + '</li>';
}
console.log(html);
$('.news').innerHTML = html;
}
function $(id){
return document.querySelector(id);
}
</script>
</html>
CORS(Cross-Origin Resource Sharing)
CORS 全稱是跨域資源共享(Cross-Origin Resource Sharing),是一種 ajax 跨域請求資源的方式,支持現(xiàn)代瀏覽器,IE支持10以上。 實現(xiàn)方式很簡單,當(dāng)你使用 XMLHttpRequest 發(fā)送請求時,瀏覽器發(fā)現(xiàn)該請求不符合同源策略,會給該請求加一個請求頭:Origin,后臺進行一系列處理,如果確定接受請求則在返回結(jié)果中加入一個響應(yīng)頭:Access-Control-Allow-Origin; 瀏覽器判斷該相應(yīng)頭中是否包含 Origin 的值,如果有則瀏覽器會處理響應(yīng),我們就可以拿到響應(yīng)數(shù)據(jù),如果不包含瀏覽器直接駁回,這時我們無法拿到響應(yīng)數(shù)據(jù)。所以 CORS 的表象是讓你覺得它與同源的 ajax 請求沒啥區(qū)別,代碼完全一樣。
服務(wù)器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>
document.domain-降域
對于主域相同而子域不同的情況下,可以通過設(shè)置 document.domain 的辦法來解決,具體做法是可以在 http://www.example.com/a.html和http://sub.example.com/b.html兩個文件分別加上 document.domain = "a.com";然后通過 a.html 文件創(chuàng)建一個 iframe,去控制 iframe 的 window,從而進行交互,當(dāng)然這種方法只能解決主域相同而二級域名不同的情況,
a.html
<div class="ct">
<h1>使用降域?qū)崿F(xiàn)跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.jrg.com:8080/a.html">
</div>
<iframe src="http://b.jrg.com:8080/b.html" frameborder="0"></iframe>
</div>
<script>
document.querySelector('.main input').addEventListener('input',function() {
console.log(thid.value)
window.frames[0].document.querySelector('input').value = this.value;
})
document.domain = 'jrg.com'
</script>
b.html
<div class="ct">
<input id="input" type="text" placeholder="http://b.jrg.com:8080/b.html">
</div>
<script>
document.querySelector('#input').addEventListener('input',function() {
window.parent.document.querySelector('input').value = this.value
})
document.domain = 'jrg.com'
</script>
使用postMessage實現(xiàn)跨域
發(fā)送方使用postMessage方法向接收方推送消息,第一個參數(shù)為推送的內(nèi)容,第二個參數(shù)是允許被訪問的域名;接收方通過監(jiān)聽message的方法接收數(shù)據(jù)
a.html
<body>
<div class="ct">
<h1>使用postMessage實現(xiàn)跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.jrg.com:8080/a.html">
</div>
<iframe src="http://localhost:8080/b.html" frameborder="0"></iframe>
</div>
<script>
$('.main input').addEventListener('input', function () {
console.log(this.value)
window.frames[0].postMessage(this.value, '*')
})
window.addEventListener('message', function (e) {
$('.main input').value = e.data
console.log(e.data)
})
function $(id) {
return document.querySelector(id)
}
</script>
</body>
b.html
<body>
<input id="input" type="text" placeholder="http://b.jrg.com:8080/b.html">
<script>
$('#input').addEventListener('input', function () {
console.log(this.value)
window.parent.postMessage(this.value, '*')
})
window.addEventListener('message', function (e) {
$('#input').value = e.data
console.log(e.data)
})
function $(id) {
return document.querySelector(id)
}
</script>
</body>