歡迎大家關(guān)注我的其他<a >Github博客</a>和<a >csdn</a>,互相交流!
1.什么是jsonp:
JSONP(JSON with Padding)是一個(gè)非官方的協(xié)議,它允許在服務(wù)器端集成Script tags返回至客戶端,通過javascript callback的形式實(shí)現(xiàn)跨域訪問(這僅僅是JSONP簡單的實(shí)現(xiàn)形式)。
2.JSONP有什么用?
由于同源策略的限制,XmlHttpRequest只允許請求當(dāng)前源(域名、協(xié)議、端口)的資源,為了實(shí)現(xiàn)跨域請求,可以通過script標(biāo)簽實(shí)現(xiàn)跨域請求,然后在服務(wù)端輸出JSON數(shù)據(jù)并執(zhí)行回調(diào)函數(shù),從而解決了跨域的數(shù)據(jù)請求。
3.如何使用JSONP?
下邊這一DEMO實(shí)際上是JSONP的簡單表現(xiàn)形式,在客戶端聲明回調(diào)函數(shù)之后,客戶端通過script標(biāo)簽向服務(wù)器跨域請求數(shù)據(jù),然后服務(wù)端返回相應(yīng)的數(shù)據(jù)并動態(tài)執(zhí)行回調(diào)函數(shù)。
下面是我自己做的一個(gè)簡單的demo。實(shí)現(xiàn)的是306關(guān)鍵字搜索功能。采用的就是jsonp的跨域功能!
看例子
這里寫圖片描述
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>推薦搜索</title>
</head>
<body>
<p>推薦搜索</p>
<input type="text" id="val" name ="wd" >
<input type="button" id="dian" value="搜索">
<ul></ul>
<script>
function abc(res) {
var wds = res['result'];
for(var i =0,str=''; i<wds.length; i++) {
str = str + '<li>' + wds[i].word + '</li>';
}
document.getElementsByTagName('ul')[0].innerHTML = str;
}
document.getElementsByName('wd')[0].oninput = function () {
var url = 'http://sug.so.#/suggest?callback=abc&encodein=utf-8&encodeout=utf-8&format=json&word=' + this.value;
var sc = document.createElement('script');
sc.src = url;
var hd = document.getElementsByTagName('head')[0];
hd.appendChild(sc);
}
</script>
</body>
</html>