jsonp
html中可以通過script標簽引入其他域的js,利用這一特性,結合后端支持,可以實現跨域訪問接口
實現原理:
- 定義數據處理函數_fun
- 創建script標簽,src的地址執行后端接口,最后加個參數callback=fun
- 服務端在收到請求后,解析參數,計算返還數據,輸出 fun(data) 字符串。
- fun(data)會放到script標簽做為js執行。此時會調用fun函數,將data做為參數。
前端代碼:
<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>
后臺代碼:
router.get('/getFriends', function(req, res) {
var username = req.query.username ;// 通過 req.query獲取請求參數
var friends;
//根據請求參數mock數據
switch (username){
case 'ruoyu':
friends = ['小米', '小剛'];
break;
case 'hunger':
friends = ['小谷', '小花'];
break;
default:
friends = ['沒有朋友'];
}
var cb=req.query.callback;
res.send(cb+'('+JSON.stringify(friends)+')')
});
CORS
CORS 全稱是跨域資源共享(Cross-Origin Resource Sharing),是一種 ajax 跨域請求資源的方式,支持現代瀏覽器,IE支持10以上。
實現方式:
- 使用XMLHttpRequest發送請求時,服務器發現不同源會在請求中加一個請求頭Origin
- 后臺確定接受該請求,則在響應頭中加一個Access-Control-Allow-Origin
- 瀏覽器判斷該響應頭中包含origin則響應請求,沒有不響應
前端代碼:
<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>
后臺代碼:
router.get('/getFriends', function(req, res) {
var username = req.query.username ;// 通過 req.query獲取請求參數
var friends;
//根據請求參數mock數據
switch (username){
case 'ruoyu':
friends = ['小米', '小剛'];
break;
case 'hunger':
friends = ['小谷', '小花'];
break;
default:
friends = ['沒有朋友'];
}
res.header("Access-Control-Allow-Origin", "http://b.test.com:8080");
res.send(friends);
});
降域
降域的使用條件是兩個名的一級域名相同(例如: a.test.com 與 b.test.com)都同屬于test.com這個域名
測試時需使用a.test.com:8080/a.html訪問,不能使用localhost,否則會報錯:報錯信息為不能把domain設置為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>使用降域實現跨域</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;
})
//取一級域名作為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;
})
//取一級域名作為domain
document.domain = 'test.com';
</script>
</html>
PostMessage
使用window.postMessage() 實現
postMessage的原理是會向另一個地方發送信息,另一個地方通常是iframe,或者是由當前頁面彈出的窗口。參數是:信息以及表示接受消息方的來自哪個域的字符串,如果給定*便是不限定接受者的域。
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實現跨域</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>