1. 程式人生 > 程式設計 >jQuery使用jsonp實現百度搜索的示例程式碼

jQuery使用jsonp實現百度搜索的示例程式碼

專案實現:還原百度搜索功能;

專案原理:利用json回撥頁面傳參;

什麼是jsonp:就是利用<script>標籤的src地址,讓目標頁面回撥本地頁面,並且帶入引數,也解決了跨域問題;

程式碼如下:

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 () {//節流
     clearTimeout(ids);
     ids=0;
     if (script) { //刪除上一次建立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實現百度搜索的示例程式碼

最終效果:

jQuery使用jsonp實現百度搜索的示例程式碼

以上就是jQuery使用jsonp實現百度搜索的示例程式碼的詳細內容,更多關於jQuery實現百度搜索的資料請關注我們其它相關文章!