欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery使用jsonp實(shí)現(xiàn)百度搜索的示例代碼

 更新時(shí)間:2020年07月08日 10:07:38   作者:阿吉萊加雷  
這篇文章主要介紹了jQuery使用jsonp實(shí)現(xiàn)百度搜索,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下

項(xiàng)目實(shí)現(xiàn):還原百度搜索功能;

項(xiàng)目原理:利用json回調(diào)頁(yè)面?zhèn)鲄?

什么是jsonp:就是利用<script>標(biāo)簽的src地址,讓目標(biāo)頁(yè)面回調(diào)本地頁(yè)面,并且?guī)雲(yún)?shù),也解決了跨域問(wèn)題;

代碼如下:

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標(biāo)簽
      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");
     // 點(diǎn)擊x按鈕刪除搜索框內(nèi)容,并且隱藏button按鈕
     $("button").click(function () {
      $("input").val("");
      $("button").css("display", "none");
     });
     // 如果搜索框?yàn)榭談t把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();
    }
    // 遍歷數(shù)組內(nèi)容輸出
    $.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));
    });
    // 失去焦點(diǎn)隱藏搜索列表
    $(".box>.ssk").on("mouseleave", function () {
     $(".box>.ssk").css("display", "none");
    });
   }
  • 這里目標(biāo)頁(yè)面是“https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=&json=1&p=3&sid=22084_1436_13548_21120_22036_22073&req=2&csor=0&cb=callback” 向百度服務(wù)器請(qǐng)求
  • callback函數(shù)為目標(biāo)服務(wù)器的回調(diào)函數(shù),傳回來(lái)的參數(shù)data是一個(gè)對(duì)象;
  • callback回調(diào)函數(shù)中,傳回來(lái)的data中s屬性是搜索到的內(nèi)容,遍歷data.s數(shù)組,將每個(gè)元素的外層添加a標(biāo)簽,a標(biāo)簽的超鏈接為搜索到的內(nèi)容,
  • 改變a標(biāo)簽超鏈接的wd屬性就可以搜索到對(duì)應(yīng)的內(nèi)容;wd傳入的值需要進(jìn)行編碼(encodeURIComponent)處理,服務(wù)器才能給出對(duì)應(yīng)內(nèi)容的超鏈接

日常百度搜索都有wd屬性,改變wd屬性即可得到搜索

最終效果:

以上就是jQuery使用jsonp實(shí)現(xiàn)百度搜索的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于jQuery實(shí)現(xiàn)百度搜索的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論