jsonp
html中可以通過(guò)script標(biāo)簽引入其他域的js,利用這一特性,結(jié)合后端支持,可以實(shí)現(xiàn)跨域訪問(wèn)接口
實(shí)現(xiàn)原理:
- 定義數(shù)據(jù)處理函數(shù)_fun
- 創(chuàng)建script標(biāo)簽,src的地址執(zhí)行后端接口,最后加個(gè)參數(shù)callback=fun
- 服務(wù)端在收到請(qǐng)求后,解析參數(shù),計(jì)算返還數(shù)據(jù),輸出 fun(data) 字符串。
- fun(data)會(huì)放到script標(biāo)簽做為js執(zhí)行。此時(shí)會(huì)調(diào)用fun函數(shù),將data做為參數(shù)。
前端代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>news</title>
<style>
.container{
width: 900px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<ul class="news">
<li>第11日前瞻:中國(guó)沖擊4金 博爾特再戰(zhàn)</li>
<li>男雙力爭(zhēng)會(huì)師決賽 </li>
<li>女排將死磕巴西!</li>
</ul>
<button class="change">換一組</button>
</div>
<script>
$('.change').addEventListener('click',function(){
var script = document.createElement('script');
script.src = 'http://127.0.0.1/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>' + new[i] + '</li>';
}
console.log(html);
$('.news').innerHTML = html;
}
function$(id){
return document.querySelector(id);
}
</script>
</html>
后端代碼:
app.get('/getNews',function(req,res){
var news =[
"第11日前瞻:中國(guó)沖擊4金 博爾特再戰(zhàn)200米羽球",
"正直播柴飚/洪煒出戰(zhàn) 男雙力爭(zhēng)會(huì)師決賽",
"女排將死磕巴西!郎平安排男陪練模仿對(duì)方核心",
"沒(méi)有中國(guó)選手和巨星的110米欄 我們還看嗎?",
"中英上演奧運(yùn)金牌大戰(zhàn)",
"博彩賠率挺中國(guó)奪回第二紐約時(shí)報(bào):中國(guó)因?qū)κ址幎鴣G失的獎(jiǎng)牌最多",
"最“出柜”奧運(yùn)?同性之愛(ài)閃耀里約",
"下跪拜謝與洪荒之力一樣 都是真情流露"
]
var data = [];
for (var i = 0; i < 3; i++) {
var index = parse(Math,random()*news.length);
data.push(news[index]);
news.splice(index,1);
}
var cb = req.query.callback;
if(cb){
res.send(cb + '(' + JSON.stringfy(data) + ')');
}else{
res.send(data);
}
})
CORS
CORS 全稱是跨域資源共享(Cross-Origin Resource Sharing),是一種 ajax 跨域請(qǐng)求資源的方式,支持現(xiàn)代瀏覽器,IE支持10以上。
實(shí)現(xiàn)方式:
- 使用XMLHttpRequest發(fā)送請(qǐng)求時(shí),服務(wù)器發(fā)現(xiàn)不同源會(huì)在請(qǐng)求中加一個(gè)請(qǐng)求頭Origin
- 后臺(tái)確定接受該請(qǐng)求,則在響應(yīng)頭中加一個(gè)Access-Control-Allow-Origin
- 瀏覽器判斷該響應(yīng)頭中包含origin則響應(yīng)請(qǐng)求,沒(méi)有不響應(yīng)
前端代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>news</title>
<style>
.container{
width: 900px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<ul class="news">
<li>第11日前瞻:中國(guó)沖擊4金 博爾特再戰(zhàn)</li>
<li>男雙力爭(zhēng)會(huì)師決賽 </li>
<li>女排將死磕巴西!</li>
</ul>
<button class="change">換一組</button>
</div>
<script>
$('.change').addEventListener('click', function(){
var xhr = new XMLHttpRequest();
xhr.open('get','http://b.jrg.com:8080/getNews',true);
xhr.send();
xhr.onreadysTatechange = function(){
if(xhr..readyState === 4 && xhr.status === 200){
appendHtml(JSON.parse(xhr.responseText))
}
}
window.xhr = xhr
})
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>
后端代碼
app.get('/getNews', function(req, res){
var news = [
"第11日前瞻:中國(guó)沖擊4金 博爾特再戰(zhàn)200米羽球",
"正直播柴飚/洪煒出戰(zhàn) 男雙力爭(zhēng)會(huì)師決賽",
"女排將死磕巴西!郎平安排男陪練模仿對(duì)方核心",
"沒(méi)有中國(guó)選手和巨星的110米欄 我們還看嗎?",
"中英上演奧運(yùn)金牌大戰(zhàn)",
"博彩賠率挺中國(guó)奪回第二紐約時(shí)報(bào):中國(guó)因?qū)κ址幎鴣G失的獎(jiǎng)牌最多",
"最“出柜”奧運(yùn)?同性之愛(ài)閃耀里約",
"下跪拜謝與洪荒之力一樣 都是真情流露"
]
var data = [];
for(var i=0; i<3; i++){
var index = parseInt(Math.random()*news.length);
data.push(news[index]);
news.splice(index, 1);
}
//res.header("Access-Control-Allow-Origin", "http://a.jrg.com:8080");
res.header("Access-Control-Allow-Origin", "*");
res.send(data);
})
降域
降域的使用條件是兩個(gè)名的一級(jí)域名相同(例如: a.test.com 與 b.test.com)都同屬于test.com這個(gè)域名
測(cè)試時(shí)需使用a.test.com:8080/a.html訪問(wèn),不能使用localhost,否則會(huì)報(bào)錯(cuò):報(bào)錯(cuò)信息為不能把domain設(shè)置為test.com
a.html
<html>
<style>
.ct {
width: 910px;
margin: auto;
}
.main {
float: left;
width: 450px;
height: 300px;
border: 1px solid #ccc;
}
.main input {
margin: 20px;
width: 200px;
}
.iframe {
float: right;
}
iframe {
width: 450px;
height: 300px;
border: 1px dashed #ccc;
}
</style>
<div class="ct">
<h1>使用降域?qū)崿F(xiàn)跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.test.com:8080/a_jiangyu.html">
</div>
<iframe src="http://b.test.com:8080/b_jiangyu.html" frameborder="0"></iframe>
</div>
<script>
//URL: http://a.jrg.com:8080/a.html
document.querySelector('.main input').addEventListener('input', function() {
console.log(this.value);
window.frames[0].document.querySelector('input').value = this.value;
})
//取一級(jí)域名作為domain
document.domain = "test.com"
</script>
</html>
b.html
<html>
<style>
html,
body {
margin: 0;
}
input {
margin: 20px;
width: 200px;
}
</style>
<input id="input" type="text" placeholder="http://b.jiangyu.com:8080/b.html">
<script>
// URL: http://b.jrg.com:8080/b.html
document.querySelector('#input').addEventListener('input', function() {
window.parent.document.querySelector('input').value = this.value;
})
//取一級(jí)域名作為domain
document.domain = 'test.com';
</script>
</html>
PostMessage
使用window.postMessage() 實(shí)現(xiàn)
postMessage的原理是會(huì)向另一個(gè)地方發(fā)送信息,另一個(gè)地方通常是iframe,或者是由當(dāng)前頁(yè)面彈出的窗口。參數(shù)是:信息以及表示接受消息方的來(lái)自哪個(gè)域的字符串,如果給定*便是不限定接受者的域。
a.html
<html>
<style>
.ct {
width: 910px;
margin: auto;
}
.ct h1 {
text-align: center;
}
.main {
float: left;
width: 450px;
height: 300px;
border: 1px solid #ccc;
}
.main input {
margin: 20px;
width: 200px;
}
.iframe {
float: right;
}
iframe {
width: 450px;
height: 300px;
border: 1px dashed #ccc;
}
</style>
<div class="ct">
<h1>使用postMessage實(shí)現(xiàn)跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.test.com:8080/a.html">
</div>
<iframe src="http://localhost:8080/b.html" frameborder="0"></iframe>
</div>
<script>
//URL: http://a.test.com:8080/a.html
$('.main input').addEventListener('input', function() {
window.frames[0].postMessage(this.value, '*');
})
window.addEventListener('message', function(e) {
$('.main input').value = e.data
});
function $(id) {
return document.querySelector(id);
}
</script>
</html>
b.html
<html>
<style>
html,
body {
margin: 0;
}
input {
margin: 20px;
width: 200px;
}
</style>
<input id="input" type="text" placeholder="http://b.test.com:8080/b.html">
<script>
// URL: http://b.test.com:8080/b.html
$('#input').addEventListener('input', function() {
window.parent.postMessage(this.value, '*');
})
window.addEventListener('message', function(e) {
$('#input').value = e.data
});
function $(id) {
return document.querySelector(id);
}
</script>
</html>