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ù)。
前端代碼:
<div class="query-area">
<input type="text" name="username" value="hunger" placeholder="hunger, ruoyu, anyone">
<button>查詢朋友</button>
</div>
<div class="detail-area">
<ul>
</ul>
</div>
<script>
var btn = document.querySelector('.query-area button');
var input = document.querySelector('.query-area input');
btn.addEventListener('click', function(){
var script=document.createElement("script");
script.src="http://a.test.com:8080/getFriends?username="+input.value+"&callback=render";
document.head.appendChild(script);
document.head.removeChild(script);
});
function render(friends){
var detailCt = document.querySelector('.detail-area ul');
detailCt.innerHTML = '';
var ct = document.createDocumentFragment();
for(var i = 0; i < friends.length; i++){
var node = document.createElement('li');
node.innerText = friends[i];
ct.appendChild(node)
}
detailCt.appendChild(ct)
}
</script>
后臺(tái)代碼:
router.get('/getFriends', function(req, res) {
var username = req.query.username ;// 通過(guò) req.query獲取請(qǐng)求參數(shù)
var friends;
//根據(jù)請(qǐng)求參數(shù)mock數(shù)據(jù)
switch (username){
case 'ruoyu':
friends = ['小米', '小剛'];
break;
case 'hunger':
friends = ['小谷', '小花'];
break;
default:
friends = ['沒(méi)有朋友'];
}
var cb=req.query.callback;
res.send(cb+'('+JSON.stringify(friends)+')')
});
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)
前端代碼:
<div class="query-area">
<input type="text" name="username" value="hunger" placeholder="hunger, ruoyu, anyone">
<button>查詢朋友</button>
</div>
<div class="detail-area">
<ul>
</ul>
</div>
<script>
var btn = document.querySelector('.query-area button');
var input = document.querySelector('.query-area input');
btn.addEventListener('click', function(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)){
var friends = JSON.parse(xhr.responseText);
render(friends)
}
};
xhr.open('get', 'http://a.test.com:8080/getFriends?username=' + input.value, true);
xhr.send();
});
function render(friends){
var detailCt = document.querySelector('.detail-area ul');
detailCt.innerHTML = '';
var ct = document.createDocumentFragment();
for(var i = 0; i < friends.length; i++){
var node = document.createElement('li');
node.innerText = friends[i];
ct.appendChild(node)
}
detailCt.appendChild(ct)
}
</script>
后臺(tái)代碼:
router.get('/getFriends', function(req, res) {
var username = req.query.username ;// 通過(guò) req.query獲取請(qǐng)求參數(shù)
var friends;
//根據(jù)請(qǐng)求參數(shù)mock數(shù)據(jù)
switch (username){
case 'ruoyu':
friends = ['小米', '小剛'];
break;
case 'hunger':
friends = ['小谷', '小花'];
break;
default:
friends = ['沒(méi)有朋友'];
}
res.header("Access-Control-Allow-Origin", "http://b.test.com:8080");
res.send(friends);
});
降域
降域的使用條件是兩個(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>