javaWeb core technology thirteenth chapter of Ajax

Js - ajax-- to explain the principles 
        outlined: asynchronous refresh the page without refreshing the entire page. 
    
    The Get principle:
                 <% @ Page Language = "the Java" contentType = "text / HTML; charset = UTF-8" 
            pageEncoding = "UTF- 8 "%> 
        ! <DOCTYPE HTML the PUBLIC" - // the W3C // DTD HTML 4.01 Transitional // EN "" http://www.w3.org/TR/html4/loose.dtd "> 
        <HTML> 
        <head> 
        <Meta HTTP-equiv = "the Type-the Content" Content = "text / HTML; charset = UTF-. 8"> 
        <title> the Insert title here Wallpaper </ title> 

        <Script> 
            function sendGetAjax () { 
                // the following code may not be You need to practice but can not use IE browser compatible 
                
                
                // 1.Obtained ajax engine 
                var = xmlHttp new new the XMLHttpRequest (); 
                
                //2. Set callback - function is invoked in response to engine ajax callback function returns the data back
                 // callback function will be performed four times 
                xmlHttp.onreadystatechange = function () {
                     // Analyzing readyState end 4 showing a state response must 
                    IF (xmlHttp.readyState ==. 4 ) {
                         // end of response necessarily be the correct response
                         @ determined to be successful response is successful status code 200 is 
                        IF (== 200 is xmlHttp.status ) {
                             // accepts values server 
                            var textTemp = the xmlHttp.responseText; 
                            Alert (textTemp); 
                        } 
                        
                        IF (xmlHttp.status == 404 ) {
                            Alert ( "yyy" ); 
                        } 
                    } 
                    
                } 
                
                // 3. Open the connection establishment of
                 // Parameter 1: Request embodiment 
                 @ Parameter 2: The route request 
                ? xmlHttp.open ( "get", " / ee66_day44 / DemoServlet username = jack2 & nickname rose2 = " ); 
                
                // 4. transmitting
                 // parameter representing a request body 
                xmlhttp.send ( null ); 
            }
         </ Script> 

        </ head> 
        <body> 
            <form Action =" / ee66_day44 / DemoServlet "Method =" POST " >
            
                <INPUT type = "text" name = "username" value = "Jack" /> 
                <INPUT type = "text" name = "Nickname" value = "Rose" /> 
                <INPUT type = "Submit" /> 
            </ form > 
            <a href="javascript:void(0)" onclick="sendGetAjax()"> point I send ajax request </a> 
        </ body> 
        </ HTML> 
    
    Post principles: 
        a similar manner with get, but need 3 4 and an intermediate setting request code plus a header. 
    
    Jquery - Ajax (key) 
        Jquery: js is the underlying features: compatible browser, api are packaged. 
        
        the Get embodiment:
                         <DOCTYPE HTML the PUBLIC "- // the W3C /! / DTD HTML 4.01 Transitional // EN " " http://www.w3.org/TR/html4/loose.dtd">
            <html>
            <head>
            <Meta HTTP-equiv = "the Content-the Type" Content = "text / HTML; charset = UTF-. 8"> 
            <title> the Insert title here Wallpaper </ title> 

            <Script type = "text / JavaScript" the src = "$ {the pageContext } /js/jquery-1.11.3.min.js .request.contextPath "> </ Script> 
            <Script> 
                function sendGetAjax () { 
                    // 1. import jquery library
                     // 2.jquery to provide tools api 
                    / ** 
                    URL: path request 
                    params: parameter request 
                        format 1: key = value & key = value ... 
                        format 2: {key: value, key : value ..} js objects 
                    fn: callback function (data) {} data It is the data callback function server response
                    type: text data of the server response indicates the default value is set if the text string is directly json data into objects 
                    * / 
                    // $ .get (URL, the params, Fn, type);
                     //
            </head>.get $ ( "/ ee66_day44 / DemoServlet"); // scenario server statistics the number of visitors
                     // $ .get ( "/ ee66_day44 / DemoServlet", "username = = rose2 jack2 & the Nickname");
                     // $ .get ( "/ ee66_day44 / DemoServlet ", {" username ":" jack3 "," Nickname ":" rose3 "}); 
                    $ .get (" / ee66_day44 / DemoServlet "," username = jack2 & Nickname = rose2 " , function (Data) { 
                        Alert ( Data); 
                    }, "text" ); 
                }
             </ Script> 

            <body> 
                <form Action = "/ ee66_day44 / DemoServlet" Method = "POST">
                
                    <input type="text" name="username" value="jack"/> 
                    <INPUT type = "text" name = "Nickname" value = "Rose" /> 
                    <INPUT type = "Submit" /> 
                </ form> 
                <A the href = "JavaScript: void (0)" the onclick = " sendGetAjax () "> point I send ajax request </a> 
            </ body> 
            </ 
            HTML > 
    
    Post: 
        . Post submission and get way there is no difference, the same parameters, as written 
        if garbled get involved and post processing is not the same, recommended post 
    
    case Study:
         1 . ajax request transmission loses focus.
         2 write function.
         3 transmits ajax request, request carries parameters. 
            parameter a username
         . 4 written in servlet code.
        5 . Callback function to process the response data
         IF (. 1Failed) { 
            username is not available, the display 
            can be used to hide 
        } the else { 
            username is not available to hide 
            the available display 
        } 
        protected  void the doGet (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException { 
        
        // 1. obtaining 
        String username = request.getParameter ( " username " );
         // 2. processing 
        IF (" Jack " .equals (username)) {
             // else return 1 
             // 3. response 
            response.getWriter () Print (." 1 " ); 
        } the else{
             // Successful return 0 
             // 3. Response 
            response.getWriter () Print ( "0." ); 
        } 
        
    
    }
    
     <Script> // page is loaded      $ (function () {
             // initialize both available and unavailable to hide 
            $ ( "#FailedId" ) .hide (); 
            $ ( "#SuccessId" ) .hide ();
             // bind event 
            $ ( "# username" ) .blur (function () {
                 // obtain parameters 
                var usernameVal = $ ( "#username" ) .val ();
                 // send a request ajax  
 
     

                .post $ ( "$ {} pageContext.request.contextPath / CheckServlet", { "username" : usernameVal}, function (Data) {
                     IF ( ". 1" == Data) {
                         // failure username is not available to display the available Hide 
                        $ ( "# SuccessId" ) .hide (); 
                        $ ( "#FailedId" ) the .Show (); 
                    } the else {
                         // successfully username is not available to hide available display 
                        $ ( "# SuccessId" ) the .Show (); 
                        $ ( "#FailedId" ) .hide (); 
                    } 
                });
            });
        })
     </script>
     
    <Div class = "COL-SM-. 4"> 
                    <span class = "label label-Success" ID = "SuccessId"> username is available </ span> 
                    <span class = "label label-Danger" ID = " FailedId "> username is not available </ span> 
    </ div> 
    
    Json (key): 
        Json is a data format for data communication to facilitate data transfer is obtained. 
        Json Object: 
            Object: format {key: value, key: value ....} use map, the object described 
        Json array: 
            Object: format [obj, obj, obj ...] using an array, list description set 
        
        in the array may be nested objects, objects can be nested arrays. 
    Js - JSON
                 <Script>
                     // JS json objects and value must be enclosed in double quotes if it is a boolean variable is not required number of double quotes
                    obj = {var "A": "B", "C": "D" };
                     // Alert (obj.c); 
                    
                    // var obj = "{ 'A': 'B', 'C': ' D '} ";
                     // Alert (obj.a);
                     // string conversion target
                     // 1.eval may convert a string of code segments into an executable
                     // 2.eval objects can be converted into a string 
                    / * objTemp the eval = var ( "(" obj + + ")"); 
                    Alert (objTemp.a); * / 
                    
                    var ARR = [ "A", "B",. 1, to true , obj];
                    alert(arr[4].a);
                    
                    
                    var obj2 = {"abc":arr};
                 </ Script> 
    
        Case Study: automatic association function 
            requirements: input value in the text box, the dynamic data is filled in the association database drop-down box.
                 1 association, the association of all the database all (query. All), details js front desk.
                 2 plus Lenovo conditions (according to criteria query).
 * /                 
                home: 
                    text box to enter the contents of
                     a text box to add events (keydown press, keypress hold down, keyup bounce) 
                        use keyup bounce event
                     2 send ajax, carrying parameters SearchWord
                     . 3 . preparation of the servlet
                     . 4 . callback data obtained 
                    will show a div, and then further adding data box,
                
                 <Script> 
                    $ (function () { 
                        // 1. text box bound to event 
                        $ ( "# SearchId") .keyup (function () {
                             // 2. Data obtained 
                            var wordVal = $ ( "# SearchId" ) .val (); 
                            
                            IF ( "" == wordVal) { 
                                $ ( "#completeShow" ) .hide ();
                                 return ; 
                            } 
                            
                            // empty UL 
                            $ ( "# ShowUI") HTML ( "." ); 
                            
                            
                            // 3. transmission request 
                            $ .post ( "$ {} pageContext.request.contextPath / SearchWordServlet", { "SearchWord" : wordVal }, function (data) {
                                 // 4. add data to traverse a div
                                 $ (Data) .each (function () {
                                     // the this current object represented by the current traversed List object represents Product <Product> 
                                    $ ( "# ShowUI"). The append ( "<class Li = 'Group-List-Item'> <a href=''> "+ the this .pname +" ( "+ the this .pinyin +") "+" </a> </ Li> " ); 
                                }); 
                                // . 5 the div displays 
                                $ ( "# completeShow" ) the .Show (); 
                                
                            }, "JSON" ); 
                        }); 
                    })
                 </script>
                
                <div id="completeShow">
                        <ULclass= "Group-List" ID = "ShowUI"> 
                        </ UL> 
                </ div> 
                
                Server: the servlet
                     . 1 . obtained 
                    obtained SearchWord
                     2 treatment. 
                    service.findByWord (SearchWord) 
                    Return Value List <class name> 
                    
                    3 response. 
                    Use JSON - lib, the set is converted into a string json 
                
                public  class SearchWordServlet the extends the HttpServlet {
                     protected  void the doGet (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException {
                        try {
                            //0.乱码
                            request.setCharacterEncoding("utf-8");
                            response.setHeader("content-type", "text/html;charset=utf-8");
                            //1.获得
                            String word = request.getParameter("searchWord");
                            //2.处理
                            ProductService  service = new ProductService();
                            List<Product> list = service.findByWord(word);
                            //3.响应
                            String json = JSONArray.fromObject(list).toString();
                            response.getWriter().print(json);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                public List<Product> findByWord(String word) throws SQLException {
                    QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
                    
                    String sql =" SELECT * FROM product WHERE pname LIKE ? OR pinyin LIKE ? ";
                    Object [] params = {
                            "%"+word+"%","%"+word+"%"
                    };
                    return queryRunner.query(sql, new BeanListHandler<Product>(Product.class), params);
                }

 

Guess you like

Origin www.cnblogs.com/haizai/p/11442988.html