jQuery使用jsonp實現(xiàn)百度搜索的示例代碼
更新時間:2020年07月08日 10:07:38 作者:阿吉萊加雷
這篇文章主要介紹了jQuery使用jsonp實現(xiàn)百度搜索,文中示例代碼非常詳細,幫助大家更好的理解和學習,感興趣的朋友可以了解下
項目實現(xiàn):還原百度搜索功能;
項目原理:利用json回調頁面?zhèn)鲄?
什么是jsonp:就是利用<script>標簽的src地址,讓目標頁面回調本地頁面,并且?guī)雲?,也解決了跨域問題;
代碼如下:
html(css代碼不提供)
<div class="box"> <input type="text" /> <div class="ssk"></div> <button>×</button> </div>
js
var script,ids; $(".box>input").on("input",inputHandler) function inputHandler(e){ if (ids) return; ids = setTimeout(function () {//節(jié)流 clearTimeout(ids); ids=0; if (script) { //刪除上一次創(chuàng)建script標簽 script.remove(); script = null; } script=$("<script><\/script>").attr("src",`https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd= ${$(".box>input").val()} &json=1&p=3&sid=22084_1436_13548_21120_22036_22073&req=2&csor=0&cb=callback` ).appendTo("body"); // 點擊x按鈕刪除搜索框內容,并且隱藏button按鈕 $("button").click(function () { $("input").val(""); $("button").css("display", "none"); }); // 如果搜索框為空則把x按鈕隱藏 if ($("input").val().length === 0) { $("button").css("display", "none"); } else { $("button").css("display", "block"); } }, 500); } function callback(data) { if (data) { $(".box>.ssk").css("display", "block"); } // 刪除上一次的搜索列表 if ($(".ssk").children().length !== 0) { $("a").remove(); } // 遍歷數組內容輸出 $.each(data.s, function (index, item) { $("<a>"+item+"</a>").appendTo(".box>.ssk"); $("a").attr('href','https://www.baidu.com/s?tn=02003390_43_hao_pg&isource=infinity&wd='+encodeURIComponent(item)); }); // 失去焦點隱藏搜索列表 $(".box>.ssk").on("mouseleave", function () { $(".box>.ssk").css("display", "none"); }); }
- 這里目標頁面是“https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=&json=1&p=3&sid=22084_1436_13548_21120_22036_22073&req=2&csor=0&cb=callback” 向百度服務器請求
- callback函數為目標服務器的回調函數,傳回來的參數data是一個對象;
- callback回調函數中,傳回來的data中s屬性是搜索到的內容,遍歷data.s數組,將每個元素的外層添加a標簽,a標簽的超鏈接為搜索到的內容,
- 改變a標簽超鏈接的wd屬性就可以搜索到對應的內容;wd傳入的值需要進行編碼(encodeURIComponent)處理,服務器才能給出對應內容的超鏈接
日常百度搜索都有wd屬性,改變wd屬性即可得到搜索
最終效果:
以上就是jQuery使用jsonp實現(xiàn)百度搜索的示例代碼的詳細內容,更多關于jQuery實現(xiàn)百度搜索的資料請關注腳本之家其它相關文章!
相關文章
jQuery 獲取除某指定對象外的其他對象 ( :not() 與.not())
這篇文章主要介紹了JQuery 獲取除某指定對象外的其他對象 ( :not() 與.not()),需要的朋友可以參考下2018-10-10