web22 ajax 站內(nèi)搜索

  • style內(nèi)部需要封號(hào);
  • 神坑(charset不是冒號(hào))response.setContentType("text/html;charset=UTF-8");
  • js改的是內(nèi)存代碼而不是源代碼
  • 所有操作都是通過(guò)ajax引擎執(zhí)行
  • 方法之中套方法外界便訪問(wèn)不到是私有
  • thread.sleep(毫秒)阻塞線程睡一會(huì)
  • json鍵值對(duì)鍵是字符串,值任意,在HTML中取屬性和Java一樣
Paste_Image.png
  • json最外不能有“”,否則就變成字符串了
  • $==jquery
  • jquery中post中文不用管,get需要按原來(lái)方式解決 (response.setContentType("text/html;charset=utf-8");)
--------查表jq看
-------get,post一樣
--------$.ajax({})里面參數(shù)隨意組合
$(function(){
        $.get(
        "/webfb22/ajaxServlet",//地址
        {"name":"zahngsan","age":25},
        function(data){
            alert("3");
            alert(data.name);
        },
        "json"
        );
//  })
    function done3(){
    $.ajax({
            url:"/webfb22/ajaxServlet",
            async:true,
            data:{"lisiwu":20},
            type:"post",
            success:function(data){
    
                alert(data.name);
            },
            error:function(){               
            },
            dataType:"json"
    });
};
Paste_Image.png
  • 局部檢驗(yàn)是否重名
- $("#checkuser").html("用戶名已存在");$("#checkuser").css("color","red");修改內(nèi)部?jī)?nèi)容和顯示顏色
- $("#username").blur(function(){})失去焦點(diǎn)
$(function(){
        $("#username").blur(function(){
        var username=$(this).val();
        $.post(
        "${pageContext.request.contextPath}/checkUserName",     
        {"username":username},
        function(data){         
        if(data.isExist){           
                $("#checkuser").html("用戶名已存在");
                $("#checkuser").css("color","red");
            }else{                              
                $("#checkuser").html("用戶名可用");
                $("#checkuser").css("color","green");
            }           
        },
        "json"
        );      
    });
});
----------------dao
public Long checkUserName(String username) throws SQLException {
        
        QueryRunner qr = new QueryRunner(MyCurrentConn.getCombpdatasource());
        String sql="select count(*) from user where username=? ";           
        return (Long) qr.query(sql, new ScalarHandler(),username);
    }
---------web
-response.getWriter().write("{\"isExist\":" + isExist + "}");注意反義
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        ProductSer pros = new ProductSer();
        boolean isExist = false;
        try {
            isExist = pros.checkUserName(username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        response.getWriter().write("{\"isExist\":" + isExist + "}");
    }
  • js可以寫(xiě)任意地方
  • 重定向
-----style="position:relative"---position:absolute;z-index:1000顯示下拉結(jié)果div
---<div style='padding:5px;cursor:pointer' onclick='clickFn(this)' onmouseover='overFn(this)' onmouseout='outFn(this)'>小手指和鼠標(biāo)不同色
<form class="navbar-form navbar-right" role="search">
                    <div class="form-group" style="position:relative">
                        <input id="search" type="text" class="form-control" placeholder="Search" onkeyup="searchWord(this)">
                        <div id="showDiv" style="display:none; position:absolute;z-index:1000;background:#fff; width:179px;border:1px solid #ccc;">
                            
                        </div>
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
                <!-- 完成異步搜索 -->
                <script type="text/javascript">
                
                    function overFn(obj){
                        $(obj).css("background","#DBEAF9");
                    }
                    function outFn(obj){
                        $(obj).css("background","#fff");
                    }
                    
                    function clickFn(obj){
                        $("#search").val($(obj).html());
                        $("#showDiv").css("display","none");
                    }
                    
                
                    function searchWord(obj){
                        //1、獲得輸入框的輸入的內(nèi)容
                        var word = $(obj).val();
                        //2、根據(jù)輸入框的內(nèi)容去數(shù)據(jù)庫(kù)中模糊查詢---List<Product>
                        var content = "";
                        $.post(
                            "${pageContext.request.contextPath}/searchWord",
                            {"word":word},
                            function(data){
                                //3、將返回的商品的名稱 現(xiàn)在showDiv中
                                //[{"pid":"1","pname":"小米 4c 官方版","market_price":8999.0,"shop_price":8999.0,"pimage":"products/1/c_0033.jpg","pdate":"2016-08-14","is_hot":1,"pdesc":"小米 4c 標(biāo)準(zhǔn)版 全網(wǎng)通 白色 移動(dòng)聯(lián)通電信4G手機(jī) 雙卡雙待 官方好好","pflag":0,"cid":"1"}]
                                if(data.length>0){
                                    for(var i=0;i<data.length;i++){
                                        content+="<div style='padding:5px;cursor:pointer' onclick='clickFn(this)' onmouseover='overFn(this)' onmouseout='outFn(this)'>"+data[i]+"</div>";
                                    }
                                    $("#showDiv").html(content);
                                    $("#showDiv").css("display","block");
                                }                               
                            },
                            "json");}</script>
------------------------------dao---記住模糊搜索是like
public List<Object> getSearchName(String str) throws SQLException {
        QueryRunner qr = new QueryRunner(MyCurrentConn.getCombpdatasource());
        String sql="select * from product where pname like ? limit 0,8";            
        List<Object> names = qr.query(sql, new ColumnListHandler("pname"),"%"+str+"%");
//      System.out.println(names.size());
        
        return names;
    }
--------web
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //獲得關(guān)鍵字
        String word = request.getParameter("word");
        
        //查詢?cè)撽P(guān)鍵字的所有商品
        ProductService service = new ProductService();
        List<Object> productList = null;
        try {
            productList = service.findProductByWord(word);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        //["xiaomi","huawei",""...]
        
        //使用json的轉(zhuǎn)換工具將對(duì)象或集合轉(zhuǎn)成json格式的字符串
        /*JSONArray fromObject = JSONArray.fromObject(productList);
        String string = fromObject.toString();
        System.out.println(string);*/
        
        Gson gson = new Gson();
        String json = gson.toJson(productList);
        System.out.println(json);
        
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(json);
        }

1.Ajax

1.什么是同步,什么是異步
同步現(xiàn)象:客戶端發(fā)送請(qǐng)求到服務(wù)器端,當(dāng)服務(wù)器返回響應(yīng)之前,客戶端都處于等待卡死狀態(tài)
異步現(xiàn)象:客戶端發(fā)送請(qǐng)求到服務(wù)器端,無(wú)論服務(wù)器是否返回響應(yīng),客戶端都可以隨意做其他事情,不會(huì)被卡死

2.Ajax的運(yùn)行原理(有一個(gè)Ajax來(lái)幫助請(qǐng)求服務(wù),只需要調(diào)用他就行)
頁(yè)面發(fā)起請(qǐng)求,會(huì)將請(qǐng)求發(fā)送給瀏覽器內(nèi)核中的Ajax引擎,Ajax引擎會(huì)提交請(qǐng)求到服務(wù)器端,在這段時(shí)間里,客戶端可以任意進(jìn)行任意操作,直到服務(wù)器端將數(shù)據(jù)返回給Ajax引擎后,會(huì)觸發(fā)你設(shè)置的事件,從而執(zhí)行自定義的js邏輯代碼完成某種頁(yè)面功能。
二、js原生的Ajax技術(shù)(了解)
js原生的Ajax其實(shí)以瀏覽器內(nèi)內(nèi)置的Ajax引擎對(duì)象學(xué)習(xí)
1)創(chuàng)建Ajax引擎對(duì)象
2)為Ajax引擎對(duì)象綁定監(jiān)聽(tīng)(監(jiān)聽(tīng)服務(wù)器已將數(shù)據(jù)響應(yīng)給引擎)
3)綁定提交地址
4)發(fā)送請(qǐng)求
5)接受響應(yīng)數(shù)據(jù)
------所用異步訪問(wèn)都是ajax引擎
function done(){
        var req=new XMLHttpRequest();
        req.onreadystatechange=function(){
            alert("2222222");
            var resp=req.response();
            alert(resp);
        };
        req.open("GET","webfb22/ajaxServlet",true);
        req.send();
    }
注意:如果是post提交
在發(fā)送請(qǐng)求之前設(shè)置一個(gè)頭
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

2.Json數(shù)據(jù)格式

  • json是一種與語(yǔ)言無(wú)關(guān)的數(shù)據(jù)交換的格式,作用:
    使用ajax進(jìn)行前后臺(tái)數(shù)據(jù)交換
    移動(dòng)端與服務(wù)端的數(shù)據(jù)交換
  • Json的格式與解析
    json有兩種格式:
    1)對(duì)象格式:{"key1":obj,"key2":obj,"key3":obj...}
    2)數(shù)組/集合格式:[obj,obj,obj...]
    json是js的原生內(nèi)容,也就意味著js可以直接取出json對(duì)象中的數(shù)據(jù)
  • Json的轉(zhuǎn)換插件直接將java對(duì)象或集合轉(zhuǎn)換成json字符串jsonlib;Gson:google;fastjson:阿里巴巴

3.Jquery的Ajax技術(shù)
jquery對(duì)js原生的ajax進(jìn)行了封裝

其中:
url:代表請(qǐng)求的服務(wù)器端地址
data:代表請(qǐng)求服務(wù)器端的數(shù)據(jù)(可以是key=value形式也可以是json格式)
callback:表示服務(wù)器端成功響應(yīng)所觸發(fā)的函數(shù)(只有正常成功返回才執(zhí)行)
type:表示服務(wù)器端返回的數(shù)據(jù)類型(jquery會(huì)根據(jù)指定的類型自動(dòng)類型轉(zhuǎn)換)
常用的返回類型:text、json、html等
3)$.ajax( { option1:value1,option2:value2... } );
常用的option有如下:
async:是否異步,默認(rèn)是true代表異步
data:發(fā)送到服務(wù)器的參數(shù),建議使用json格式
dataType:服務(wù)器端返回的數(shù)據(jù)類型,常用text和json
success:成功響應(yīng)執(zhí)行的函數(shù),對(duì)應(yīng)的類型是function類型
type:請(qǐng)求方式,POST/GET
url:請(qǐng)求服務(wù)器端地址

$.get(url, [data], [callback], [type])
$.post(url, [data], [callback], [type])
$.get(
                
        "/webfb22/ajaxServlet",//地址
        {"name":"zahngsan","age":25},
        function(data){
            alert("3");
            alert(data.name);       },
        "json"
        );
-------------------------
function done3(){
    $.ajax({
            url:"/webfb22/ajaxServlet",
            async:true,
            data:{"lisiwu":20},
            type:"post",
            success:function(data){
                alert(data.name);               
            },
            error:function(){               
            },
            dataType:"json"
    });
};
        

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容