解決瀏覽器跨域問題的幾種方法
- flash
- 服務(wù)器代理中轉(zhuǎn)
- Jsonp
- document.domain(針對基礎(chǔ)域名相同的情況)
這篇博客主要介紹Jsonp
Josnp
JSONP(JSON with Padding)是JSON的一種“使用模式”凤优,可用于解決主流瀏覽器的跨域數(shù)據(jù)訪問的問題肌稻。由于同源策略俐载,一般來說位于 server1.example.com 的網(wǎng)頁無法與不是 server1.example.com的服務(wù)器溝通慢睡,而 HTML 的< script > 元素是一個例外金赦。利用 < script > 元素的這個開放策略,網(wǎng)頁可以得到從其他來源動態(tài)產(chǎn)生的 JSON 資料菌赖,而這種使用模式就是所謂的 JSONP伴郁。
Jsonp原理
Web頁面上用< script > 引入 js文件時則不受是否跨域的影響
(不僅如此,我們還發(fā)現(xiàn)凡是擁有"src"這個屬性的標(biāo)簽都擁有跨域的能力秸脱,比如< script >芳绩、< img >、< iframe >)于是我們把數(shù)據(jù)放到服務(wù)器上撞反,并且數(shù)據(jù)為json形式(因為js可以輕松處理json數(shù)據(jù))
因為我們無法監(jiān)控通過< script >的src屬性是否把數(shù)據(jù)獲取完成,所以我們需要做一個處理搪花。
實現(xiàn)定義好處理跨域獲取數(shù)據(jù)的函數(shù)遏片,如 function doJSON(data){ }。
用src獲取數(shù)據(jù)的時候添加一個參數(shù)cb=‘doJSON’ (服務(wù)端會根據(jù)參數(shù)cb的值返回 對應(yīng)的內(nèi)容) 此內(nèi)容為以cb對應(yīng)的值doJSON為函數(shù)真實要傳遞的數(shù)據(jù)為函數(shù)的參數(shù)的一串字符 如 doJSON(’數(shù)據(jù)’)
百度搜索框
使用Jsonp做一個百度搜索框
完成效果:
這里寫圖片描述
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>百度搜索框</title>
<style>
*{
margin: 0;
padding: 0;
text-decoration: none;
list-style: none;
}
#box{
width: 400px;
margin: 50px auto;
}
#inp {
width: 400px;
height: 20px;
line-height: 20px;
}
ul{
display: none;
}
a{
color: red;
}
</style>
</head>
<body>
<div id="box">
<input type="text" id="inp">
<ul id="uu"></ul>
</div>
<script>
function xx (data) {
console.log(data);//看看傳回來的數(shù)據(jù)形式
ul.innerHTML='';
var arr = data.s;//發(fā)現(xiàn)s屬性是傳回來的數(shù)據(jù)
var df = document.createDocumentFragment();//創(chuàng)建文檔碎片
if(!data || !arr) {
ul.style.display = 'none';
}else {
ul.style.display = 'block';
arr.forEach(function (keyCode){//遍歷元素, 及插入節(jié)點
var oLi = document.createElement('li');
var oA = document.createElement('a');
oA.setAttribute('href', 'https://www.baidu.com/s?wd=' + keyCode);
oA.innerText = keyCode;
oLi.appendChild(oA);
df.appendChild(oLi);
})
ul.appendChild(df);
}
}
var ul = document.getElementById('uu');
var input = document.getElementById('inp');
input.onkeyup = function (){
if(input.value == '') {
ul.style.display = 'none';
}else{
var oScript = document.createElement('script');//通過script標(biāo)簽獲取數(shù)據(jù)
oScript.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' + input.value + '&cb=xx';
document.body.appendChild(oScript);
oScript.remove();//獲取完數(shù)據(jù)將標(biāo)簽刪除
}
}
</script>
<!-- <script src='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=beio&cb=xx'></script> -->
</body>
</html>