怎麼樣把百度搜尋引入自己的網站JS實現(附原始碼)

來源:互聯網
上載者:User

請穩步我的部落格查閱並下載所有資源以及原始碼 http://www.cckan.net

 

大家都見過這種效果吧

怎麼樣把他引入到自己的網站裡面呢?下面咱們一起來分析一下吧

使用Ie9的”開發工具“可可以輕鬆擷取到,在你輸入一個關鍵字時百度是怎麼擷取智能提示,就是相關的關鍵字的。

一起來看一下吧

大家可以清楚的看到在我們每次修改查詢方塊時,百度就是發一個Ajax請求去調相應的資料

地址就是:http://suggestion.baidu.com/su?wd=部落格&p=3&cb=window.bdsug.sug&t=1324271669786

大家不難看出來吧,wd=部落格 這個部落格 就是我輸入的關鍵字,如果你想使用其它的關鍵字的話,只需要動太的修改wd的值就行了。

這時大家一定會這樣想,我們是不是只要發一個Get請求,只要每次在我們自己的網站上查詢時動態發一個Ajax請求去訪問這個地址就行了呢?是的,

但大家一個不要傻著去使用Http請求,因為這樣的請求是從你的伺服器發起的,當然百度肯定是會封你的。

我們需要怎麼做才能避免這個問題呢?

那就只有一個方法了,使用Js,在用戶端執行請求。因為Js是在用戶端發起的,就算是百度封的話,那它封的是所有過量使用你網站的使用者,相信百度不會傻到這點上吧。因為這樣他們失去很多使用者

所以這個方法應該 是成立的

但是大家都知道Js是不能跨越訪問的,而百度又不可能給你跨越的介面,或者是許可權,我們應該怎麼辦呢?

簡單,我們上面也看到了,Baidu給我們的是一個Jsonp的資料格式,那麼我們就可以直接使用Jsonp的方法去發起Ajax請求了,因為返回Jsop格式資料的JS是可以跨越訪問的

大家一起來看下My Code吧。

function FillUrls() {    var strdomin = $.trim($("#Text1").val());    var qsData = { 'wd': strdomin, 'p': '3', 'cb': 'ShowDiv', 't': '1324113456725' };    $.ajax({        async: false,        url: "http://suggestion.baidu.com/su",        type: "GET",        dataType: 'jsonp',        jsonp: 'jsoncallback',        data: qsData,        timeout: 5000,        success: function (json) {        },        error: function (xhr) {            alert(xhr);        }    });}

 

代碼很簡單大家一看應該就明白了,我只解釋一下這句吧

var qsData = { 'wd': strdomin, 'p': '3', 'cb': 'ShowDiv', 't': '1324113456725' };

wd是我們要輸入的關鍵字。

p  和就不用管了

cb是什麼呢?是Ajax返回是直接調用的方法,個是百度返回的資料裡面會執行方法進行調用,我們不用做任何的處理

只需要寫一個方法接受資料就行了

function ShowDiv(strurls) {    var urls = strurls["s"];   }

 

urls 這個就是我們需要的資料,我們一起來看看調用後返回的資料是什麼樣式的吧

ShowDiv({q:"部落格",p:false,s:["部落格中國","部落格園","部落格大巴","部落格網","部落格登陸","部落格註冊","部落格搜尋","部落格群發","部落格 新浪","部落格群發大師"]});
複製代碼

這就是百度返回的資料,我們只需要s後面的資料就行了,現在應該明白我寫var urls = strurls["s"]; 這句的意思了吧。

在個時候大家可以自己試試了。

因為百度只返回的資料,所以我們還要做一個智能提供的框,當然也就可以自己定義樣子了。先來看看這個框吧

 <div style="display: none; position: absolute;" id="allSitesBoxHdl" class="classlist"        onmouseover="this.style.display='block'" onmouseout="this.style.display='none'">        <ul id="allSitesBoxContent">        </ul>    </div>複製代碼

樣式如下

View Code #allSitesBoxHdl.classlist{    position: absolute;    background-color: #F5FBFF;    width: 256px;    border: 1px solid #C9E4F4;    top: 28px;    left: 0;    text-align: left;    font-size: 14px;    line-height: 30px;    padding: 1px;}#allSitesBoxHdl.classlist li{    display: inline;}#allSitesBoxHdl.classlist li.lis a{    text-decoration: none;    height: 30px;    width: 210px;    float: left;    padding-left: 8px;    color: #666;}#allSitesBoxHdl.classlist li.lis a:hover{    color: #016493;    background-color: #edf6fb;}#allSitesBoxHdl.classlist li.lis a:active{    color: #016493;    background-color: #edf6fb;}#allSitesBoxHdl.classlist li.lis input{    cursor: pointer;    color: #FF6600;    border-right: 1px solid #ccc;    border-bottom: 1px solid #ccc;    height: 22px;    margin: 4px;    line-height: 22px;    float: right;    background: #fff;}.wena{    color: #666;    font-size: 12px;    height: 30px;    line-height: 30px;    width: 250px;    float: left;}複製代碼

第一步我們需要一個註冊事件來完成控制項的一些效果事件的綁定,當我們輸入資料時才能的效果

方法如下

//註冊對象的事件function Init() {    $("#allSitesBoxHdl")[0].style.display = "none";     $(":text").each(function () {        if ($(this)[0].getAttribute('url') == 'true') {//給所有的text加屬性            $(this).bind("keyup", OnKeyup); //按鍵時            $(this).bind("mousedown", BoxShowUrls); //滑鼠安下時            $(this).bind("mouseout", BoxHide); //滑鼠離開時            $(this).bind("paste", OnPaste); //處理http;//            $(this)[0].setAttribute("autocomplete", "off");        }    });}複製代碼

這個方法這句 if ($(this)[0].getAttribute('url') == 'true') {//給所有的url=true屬性的Text加效果

的意思是,我們所有引用這個網頁的Text框中,只要有一個屬性是url='true'的都會實現這個效果,也就是說我們只要把樣式和Js檔案引入一下,然後想讓那具控制項顯示就直接添加一個屬性

url='true'就行了,別的什麼也不需要做了。是不是很方便啊。

一起來看看Binder 方法的實現吧

下面是整個Js檔案(這裡還包括一個同時輸入多個文字框的效果)

View Code //-----------------------------------------實現多個輸入框同時輸入的方法-----------------------------------------------//得到控制項IDfunction getid(id) {    return (typeof id == 'string') ? document.getElementById(id) : id};function getOffsetTop(el, p) {    var _t = el.offsetTop;    while (el = el.offsetParent) {        if (el == p) break;        _t += el.offsetTop    }    return _t};function getOffsetLeft(el, p) {    var _l = el.offsetLeft;    while (el = el.offsetParent) {        if (el == p) break;        _l += el.offsetLeft    }    return _l};var currentInput = null;//修改屬性顯示列表function BoxShow(e) {    var input = e;    if (!input.id) {        input = e.target ? e.target : e.srcElement;    }    currentInput = input;    FillUrls();    var box = getid("allSitesBoxHdl");    if (box.style.display == 'block' && currentInput.id == input.id) {        return;    }    box.style.left = (getOffsetLeft(input)) + 'px';    box.style.top = (getOffsetTop(input) + (input.offsetHeight - 1)) + 'px';    box.style.width = (input.offsetWidth - 4) + 'px';    box.style.display = 'block';}//顯示列表function BoxShowUrls(e) {    var input = e;    if (!input.id) {        input = e.target ? e.target : e.srcElement;    }        BoxShow(e);}//給Input設定值function InputSetValue(val) {    var obj = currentInput;    obj.value = val;    if (obj.getAttribute('url') == 'true') {        var tags = document.getElementsByTagName('input');        for (var i = 0; i < tags.length; i++) {            if (tags[i].getAttribute('url') == 'true' && tags[i] != obj) {                tags[i].value = val;            }        }    }    BoxHide();}function BoxHide() {    if (getid("allSitesBoxHdl")) {        getid("allSitesBoxHdl").style.display = 'none';    }}//載入列表function FillUrls() {    var strdomin = $.trim($("#Text1").val());    var qsData = { 'wd': strdomin, 'p': '3', 'cb': 'ShowDiv', 't': '1324113456725' };    $.ajax({        async: false,        url: "http://suggestion.baidu.com/su",        type: "GET",        dataType: 'jsonp',        jsonp: 'jsoncallback',        data: qsData,        timeout: 5000,        success: function (json) {        },        error: function (xhr) {            alert(xhr);        }    });}function ShowDiv(strurls) {    var urls = strurls["s"];    var html = "";    if (urls) {        var urllist = urls;        var forlength = 0;        var stringcookie;        for (var i = urllist.length - 1; i >= 0; i--) {            var textval = urllist[i];            if ($.trim(textval) != "" && $.trim(textval) != "undefined") {                html += "<li class=\"lis\"><a href=\"javascript:InputSetValue('" + textval + "');\">" + textval + "</a></li><br/>";            }        }    } else {        html = "<li style='font-size: 12px;' >  沒有記錄</li>";    }    if ($.trim(html) == "") {        html = "<li style='font-size: 12px;' >  沒有記錄</li>";    }    getid("allSitesBoxContent").innerHTML = html;}//關閉IMEfunction closeIME(e) {    var obj = e.target ? e.target : e.srcElement;    obj.style.imeMode = 'disabled';}function OnPaste(e) {    var obj = e.target ? e.target : e.srcElement;    setTimeout("MoveHttp('" + obj.id + "')", 100);}//修正URLfunction MoveHttp(id) {    var val = getid(id).value;    val = val.replace("http://", "");    if (val[val.length - 1] == '/') {        val = val.substring(0, val.length - 1);    }    getid(id).value = val;}function OnKeyup(e) {    var obj = e.target ? e.target : e.srcElement;    setTimeout("addInput('" + obj.id + "')", 200);}//賦值function addInput(id) {    var obj = getid(id);    //如果是一個沒有True的input不執行    if (obj.getAttribute('url') == 'true') {        if (obj.value.indexOf('。') > 0) {            obj.value = obj.value.replace('。', '.');        }        var tags = document.getElementsByTagName('input');        for (var i = 0; i < tags.length; i++) {            if (tags[i].getAttribute('url') == 'true' && tags[i] != obj) {                tags[i].value = obj.value;            }        }    }    FillUrls();}//註冊對象的事件function Init() {    $("#allSitesBoxHdl")[0].style.display = "none";     $(":text").each(function () {        if ($(this)[0].getAttribute('url') == 'true') {//給所有的url=true屬性的Text加效果            $(this).bind("keyup", OnKeyup); //按鍵時            $(this).bind("mousedown", BoxShowUrls); //滑鼠安下時            $(this).bind("mouseout", BoxHide); //滑鼠離開時            $(this).bind("paste", OnPaste); //處理http;//            $(this)[0].setAttribute("autocomplete", "off");        }    });}複製代碼

網頁代碼如下:

View Code <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title>    <link href="Scripts/StyleSheet.css" rel="stylesheet" type="text/css" />    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>    <script src="Scripts/JScript2.js" type="text/javascript"></script></head><body>    <form style="text-align: center" id="form1" runat="server">    <br />  <br />  <br />  <br />  <br />  <br />  <br />    <input style="width:500px;"  url="true" id="Text1" type="text" /><br/>       <input style="width:500px;" id="Text2" type="text" />    <div style="display: none; position: absolute;" id="allSitesBoxHdl" class="classlist"        onmouseover="this.style.display='block'" onmouseout="this.style.display='none'">        <ul id="allSitesBoxContent">        </ul>    </div>    <script type="text/javascript">        Init();</script>    </form></body></html>複製代碼

好了我們一起瀏覽一下效果吧

是不是很拉風啊。

說到這裡不僅僅是百度這樣,像Soso,Sogou等都可以使用同樣的方法來實現。

大家如有興趣的話可以下載這個例子看看。:http://download.csdn.net/detail/sufei1013/3949230

如果感覺不錯的話就給小弟推薦一下吧。

-------------------------------------------------------------簽名部分--------------------------------------------------------------

                         

         歡迎大家轉載,如有轉載請註明文章來自:  
http://sufei.cnblogs.com/  

簽名:做一番一生引以為豪的事業;在有生之年報答幫過我的人;並有能力協助需要協助的人;    


-----------------------------------------------------------推薦文章--------------------------------------------------------

  • 上一篇:網站設計常用技巧收集
  • 下一篇:最近網友QQ聯絡我解決問題的鬱悶
  • 3
    0

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.