JSONP練習
本文內容過于簡陋,只是單純的記錄一下 JSONP 的練習代碼:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSONP練習</title>
<script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<input type="text" placeholder="請輸入要搜索的內容"/>
<ul></ul>
<script>
/*
jQuery1102031111030815926477_1559740511411(
{
"q":"i",
"p":false,
"g":[
{"type":"sug","sa":"s_1","q":"ins"},
{"type":"sug","sa":"s_2","q":"iphone"},
{"type":"sug","sa":"s_3","q":"ig"},
{"type":"sug","sa":"s_4","q":"iphone x"},
{"type":"sug","sa":"s_5","q":"ieee"},
{"type":"sug","sa":"s_6","q":"iu"},
{"type":"sug","sa":"s_7","q":"it"},
{"type":"sug","sa":"s_8","q":"ipo"},
{"type":"sug","sa":"s_9","q":"ipad"},
{"type":"sug","sa":"s_10","q":"ipados"}
]
}
);
https://www.baidu.com/sugrec?prod=pc&from=pc_web&wd=i&cb=jQuery1102031111030815926477_1559740511411
*/
let $ul = $("ul");
$("input").on("input", function () {
// console.log(this.value);
$.ajax({
url: "https://www.baidu.com/sugrec?prod=pc&from=pc_web&wd=" + this.value,
data: {
"teacher": "BNTang",
"age": 34
},
// 告訴jQuery需要請求跨域的數據
dataType: "jsonp",
// 告訴jQuery服務器在獲取回調函數名稱的時候需要用什么key來獲取
jsonp: "cb",
success: function (msg) {
// console.log(msg);
createItems(msg.g);
}
});
});
function createItems(list) {
$("ul>li").remove();
for (let i = 0; i < list.length; i++) {
let $li = $("<li>" + list[i].q + "</li>");
$ul.append($li);
}
}
</script>
</body>
</html>

浙公網安備 33010602011771號