用jsonp實現搜索框功能


用jsonp實現搜索框功能

前面的話:

    在上周本來想發一篇模仿必應搜索的界面。但是在准備寫文章之前突然想到前面學習了ajax技術,在這里我也讓我的頁面有一種不需要手動刷新就能獲取到數據。但是發現用前面的方法並不能獲取到我想要的效果。無奈前幾天電腦換系統,把之前的源碼丟了(前面有個不好的習慣就是把最近在做的東西放桌面)。今天想徹底把這個問題搞明白。

用jquery和ajax進行初步的嘗試:

(本代碼是參考慕課網,搜索框制作視頻制作,有關具體詳情請參考視頻。自己之前的代碼找不到了,之前最先的想法也是來自那里,所以這次直接用那里的代碼)
html代碼:

    <div class="bg-div">  
        <div class="search-box">  
            <div class="logo"></div>  
            <form id="search-form">  
                <input type="text" class="search-input-text" autocomplete="off" name="q" id="search_input" />  
                <input type="submit" class="search-input-button" value="" id="search_submit">  
            </form>  
        </div>  
    </div>  
      
    <div class="suggest" id="search-suggest" <!--style="display:none;"-->>  
        <ul id="search-result">  
            <li>搜索結果1</li>  
            <li>搜索結果2</li>  
        </ul>  
    </div>  

css代碼:

* {  
    padding: 0;  
    margin: 0;  
}  
 
body {  
     
}  
 
.bg-div{  
    background-image: url('images/river.jpg');  
    width: 1228px;  
    height: 690px;  
    margin: 0 auto;  
    position: relative;  
}  
 
.logo {  
    background-image: url('images/logo.png');  
    width: 107px;  
    height: 53px;  
    float: left;  
    margin: -4px 18px 0 0;  
}  
 
form {  
    float: left;  
    background-color: #fff;  
    padding: 5px;  
}  
 
.search-input-text {  
    border: 0;  
    float: left;  
    height: 25px;  
    line-height: 25px;  
    outline: none;  
    width: 350px;  
    font-size: 16px;  
}  
 
.search-input-button {  
    border: 0;  
    background-image: url('images/search-button.png');  
    width: 29px;  
    height: 29px;  
    float: left;  
}  
 
.search-box {  
    position: absolute;  
    top: 200px;  
    left: 300px;  
}  
 
#search-suggest {  
    width: 388px;  
    background-color: #fff;  
    border: 1px solid #999;  
    display: none;  
}  
 
.suggest ul {  
    list-style: none;  
}  
 
.suggest ul li {  
    padding: 3px;  
    font-size: 14px;  
    line-height: 25px;  
    cursor: pointer;/*手型*/  
    /*這段代碼去掉
    position:absolute;
    left:----px;
    top:----px;
     */
}  
 
.suggest ul li:hover {  
    text-decoration: underline;  
    background-color: #e5e5e5;  
} 

 用jquery來實現效果:

在這之前,我們基本上得到了我們想要的圖形效果,但是我們在搜索框內輸入想要查詢的內容這時候是不會有效果的(一般的搜索框效果都是在鍵盤輸入的時候,下面會顯示一部分與之關聯的關鍵搜索信息,然后鼠標移動上去點擊后會跳到相應鏈接)。為了一步步驗證我們的思路,我們這里修改一下之前的代碼,

1、將li標簽中的定位去掉;2、在html中將li標簽設置為隱藏。然后我們進行后面的操作。

思考一:如何在鍵盤輸入的時候就顯示相關信息(即:li標簽中的內容)?

思路:我們先引入jquery,然后文檔加載完后執行一個鍵盤事件,然后在鍵盤事件中改變相應的css效果

$(function() {
    //鍵盤事件
    $("#search_input").bind("keyup", function() {
                $("#search-suggest").show().css({
                    top : $("#search-form").offset().top + $("#search-form").height()+10,
                    left : $("#search-form").offset().left,
                    position : "absolute",
                });
    });
});

這時候,我們在搜索框中輸入內容時,下面會跟着顯示對應的搜索(模擬)

思考二:如何實現鼠標點擊搜索按鈕的時候,會搜索相應的內容?

思路:用鼠標點擊事件,讓鼠標點擊后設置一個地址,點擊后直接跳到相應地址,代碼實現:

    //事件代理  --》鼠標點擊事件
    $(document).delegate("li", "click", function() {
        var keyword = $(this).text();
        location.href = "http://cn.bing.com/search?q=" + keyword;
    });

思考三:我們如何在搜索框輸入數據時,下面會提示相關搜素信息?
思路:我們我們用jquery中的get去實現,參考代碼:

        var searchText = $("#search_input").val();
        $.get( "http://api.bing.com/qsonhs.aspx?q="+searchText , function(data) {
                console.log(data);
                var d = data.AS.Results[0].Suggests;
                var html = "";
                for(var i = 0; i < d.length; i++) {
                    html += "<li>"+d[i].Txt+"</li>";
                }
                $("#search-result").html(html);
            }
            , "json");

到這里,按理來說我們這里應該可以得到我們想要的結果了,但是,找了好久都沒有發現哪里錯了。視頻里面接着描述了用JSONP來進行跨域操作,但是我也按視頻中的操作,始終得不到我想要的結果,於是我埋頭去看《javascript高級程序設計》,去找關於jsonp的用法

關於jsonp:

    關於jsonp,《javascript高級程序設計》一書中介紹的比較少,下面是我看了之后的歸納。
    jsonp的全寫是 json with padding,其出現是為了解決各主瀏覽器的之間的同源策略的問題,一般來說ServerA 域下面的頁面是沒有辦法與非 ServerA 下面的資源進行溝通,而 Html 的<script>元素是個例外,利用 <script> 這個開源策略,網頁可以從其他來源動態獲取 json數據,而這種模式就是所謂的 JSONP,用 jsonp 抓到並不是真正意義上 的 json 而是任意的 javascript ,它是直接通過 javascript 編譯器編譯而不是 json 解釋器。更多關於json的知識請點擊:http://www.cnblogs.com/foodoir/p/5894760.html查看
    
既然書上沒有寫,那就去網上搜索資源。這里截取一段和文章前面有關的信息的代碼:

        $.ajax({
             type: "get",
             async: false,
             url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998",
             dataType: "jsonp",
             jsonp: "callback",//傳遞給請求處理程序或頁面的,用以獲得jsonp回調函數名的參數名(一般默認為:callback)             
             jsonpCallback:"flightHandler",//自定義的jsonp回調函數名稱,默認為jQuery自動生成的隨機函數名,也可以寫"?",jQuery會自動為你處理數據            
    success: function(json){
                 alert(json.price +  json.tickets + ' 張。');
             },
             error: function(){
                 alert('fail');
             }
         });

通過這段代碼來修改我們自己的代碼:

       $.ajax({
            type: "GET",
            url: "http://api.bing.com/qsonhs.aspx?type=cb&q=" + searchText,
            dataType: "jsonp",
            jsonp: 'cb',
            success: function(data) {
                var d = data.AS.Results[0].Suggests;
                var html = "";

                for(var i = 0; i < d.length; i++) {

                    html += "<li>" + d[i].Txt + "</li>";
                }
                $("#search-result").html(html);

                $("#search-suggest").show().css({
                    top: $("#search-form").offset().top + $("#search-form").height() + 10,
                    left: $("#search-form").offset().left,
                    position: "absolute",
                });
            }
        })    

更多思考:我們可以在前面增加一些判斷,讓我們的效果實現起來更完美

                if(data == null) {
                    $("#search-suggest").hide();
                    return false;
                }
                if(data.AS == null) {
                    $("#search-suggest").hide();
                    return false;
                }
                if(data.AS.Results == null) {
                    $("#search-suggest").hide();
                    return false;
                }
                if(data.AS.Results[0] == null) {
                    $("#search-suggest").hide();
                    return false;
                }
                if(data.AS.Results[0].Suggests == null) {
                    $("#search-suggest").hide();
                    return false;
                }   

 

經過測試前面的代碼,發現還有不足,進一步修改代碼:

    $("#search-form").submit(function() {
        var keyword = $("#search_input").val();
        console.log("word=" + keyword);
        //if (keyword == null) {return false;}  
        location.href = "http://cn.bing.com/search?q=" + keyword;
    });

到這里,我們的效果差不多就出來了,效果截圖:

源代碼已托管至:http://sandbox.runjs.cn/show/gfdpkysk,點擊即可查看。

后面的話:

  這些天學習的新東西挺多的,現在有一個想法就是把最近學的東西把它串聯起來,做一個綜合的效果。參考必應網站,真的有好多東西已經可以做出來了,接下來的一段時間就好好的把自己想要做的效果實現好。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM