jsonp跨域訪問接口
雖然js是受到同源策略,但是引用js文件,img,css文件是不會(huì)受到限制的。我們可以利用標(biāo)簽的src屬性這個(gè)特點(diǎn),動(dòng)態(tài)的創(chuàng)建script標(biāo)簽,通過src屬性發(fā)送相關(guān)的請(qǐng)求,請(qǐng)求的時(shí)候,返回回來的數(shù)據(jù),是一個(gè)函數(shù)調(diào)用,會(huì)被當(dāng)作JS代碼執(zhí)行,所以只要我們提前聲明好和返回的函數(shù)調(diào)用同名的函數(shù),那么在數(shù)據(jù)請(qǐng)求成功之后,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
list-style-type: none;
}
.box {
width: 250px;
height: 40px;
border: 1px solid #ccc;
border-radius: 5px;
position: absolute;
top: 100px;
left: 50%;
margin-left: -125px;
}
.box input {
height: 100%;
width: 100%;
border: none;
text-indent: 10px;
outline: none;
}
.box ul {
position: absolute;
width: 100%;
top: 40px;
left: 0;
border: 1px solid #ccc;
border-top: none;
display: none;
}
.box ul li {
height: 40px;
line-height: 40px;
border-bottom: 1px solid #ccc;
text-indent: 10px;
}
</style>
</head>
<body>
<div class='box'>
<input type="text" placeholder="請(qǐng)輸入搜索內(nèi)容" value="">
<ul></ul>
</div>
<script type="text/javascript" src="art-template.js"></script>
<script type="text/template" id="tpl">
{{each result}}
<li>
<a id="">{{$value.word}}</a>
</li>
{{/each}}
</script>
<script type="text/javascript">
window.onload = function () {
var input = document.querySelector('input');
var ul = document.querySelector('ul');
//將這個(gè)作為window的屬性,這樣的話在哪里都可以調(diào)用的到
window.suggest_so = function (data) {
ul.innerHTML = template('tpl',data);
}
input.onkeyup = function () {
var val = this.value;
//當(dāng)輸入的值為空的時(shí)候隱藏ul
if(val == "") {
ul.style.display = "none";
} else {
ul.style.display = "block";
}
//創(chuàng)建一個(gè)script標(biāo)簽,讓這個(gè)標(biāo)簽發(fā)出請(qǐng)求
var script = document.createElement('script');
script.src = 'https://sug.so.#/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word='+val;
document.body.appendChild(script);
document.body.removeChild(script);
}
}
</script>
</body>
</html>