先寫個簡易的demo瞭解下jsonp的原理
接下來看看百度是如何實現搜索的
將鏈接打開獲得以下內容:
這裏和前面的原理是一樣的,能獲取json對象
sp0.baidu.com是百度的二級域名
https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su是百度搜索的接口
這裏我們只需要傳遞關鍵詞,修改下cb換成自己的getvalue方法:
https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=csdn&cb=getvalue
//實現智能提示
$("input.wd").on("input",function(){
//清空https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=爲開頭的script
$("script[src^='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=']").detach();
//跨域百度搜索
$("<script src='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+$(".wd").val()+"&cb=getvalue'>").appendTo("head");
});
結果就出來了,開心(*^▽^*)
接下來就是將結果附在搜索欄下方
function getvalue(json){
//先清空前面的搜索結果
$(".search-result").html("");
//再將當前的搜索結果附上去
json.s.forEach(function(s){
$(".search-result").append($("<li>"+s+"</li>"));
});
}
哈哈哈!完成!!☟☟☟
使用jsonp就更簡單了
$(".wd").on("input",function () {
var text = $(this).val();
//藉助script標籤漏洞,實現跨域請求
$.ajax({
url:"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+text+"&cb=getvalue",
dataType:"jsonp",
type:"post",
jsonp:"cb",
success:function (data) {
console.log(data);
},
error:function (err) {
}
});
});