15th Chapter Web15-ajax and jquery Cases

Source: Internet
Author: User

Today's mission
? Using AJAX to perform asynchronous validation of user names
? Using jquery to complete the user name asynchronous checksum
? Use jquery to complete product information blur display
? Use jquery to complete provincial and municipal linkage effects return XML
? Use jquery to complete the provincial and municipal linkage effect return JSON
Teaching navigation
Teaching objectives
Understand the basic use of Ajax
Mastering the Ajax part of jquery code
Mastering jquery returns how XML and JSON format data are handled
Teaching methods
Case-driven approach
1.1 Previous lesson Content review:
JDBC adds, modifies, and deletes queries.

  • Inquire:
    • On the first page click Query: Submit to servlet--call business Layer--Invoke DAO
  • Add to:
    • On the home page click Add: Submit to the added JSP. Enter some information in the JSP. Commit to servlet.
      • Receive parameters in the servlet, encapsulate parameters, call the business layer, call DAO.
      • Use the token mechanism to complete the recurring commit problem.
  • Modify:
    • On the list page, click Edit: Submit to servlet. Query for an item. Display to page.
      • Enter some information in the page and click OK. Commit to the modified servlet.
      • Receive parameters, encapsulate, call the business layer, call DAO.
  • Delete:
    • In the list page, click Delete: Submit to servlet.
      • Receives the ID in the servlet, invokes the business layer, and calls DAO.
      • Use JS to prompt.
  • Paging query:
    • Pagination Category:
      • Query a few records at once.
      • Query all records at once. Slice the records.
    • One-time query several: limit
    • To encapsulate a paged bean:
      • Supply parameters: Currpage,pagesize,totalcount,totalpage,list.
    • The Pagebean needs to be encapsulated at the business level.
      1.2 Using AJAX to complete the user name asynchronous checksum: 1.2.1 Requirements:

      On the registration page, when the user name is entered, the cursor leaves the text box, indicating whether the user name already exists.
      If the user name already exists, it needs to be queried in the background database.
      1.2.2 Analysis: 1.2.2.1 Technical Analysis:
      "Overview of Ajax"
      ? The concept of Ajax:

      Ajax uses old technology, new ideas. The application of RIA was completed: Rich Internet application.
  • Traditional way of development: all data is submitted to the server side for processing. (Fat server)
  • Ajax Way to develop: there is part of the code written on the client.
    Synchronous:
    Asynchronous:
    ? The role of Ajax:
    Completes a local refresh of the page without affecting the user's experience.
  • Check whether the user name already exists
  • Baidu Information Input Tips
    ...
    ? Using Ajax:
    JavaScript and XML
  • XMLHttpRequest:
    • Property:
      • onReadyStateChange:
      • ReadyState:
      • Status: Get State code
      • ResponseText: Text of the response
      • Responsexml: The XML of the response
    • Method:
      • Open ("Request Method", "Request Path", "whether Async");
      • Send ("submitted parameters");
      • setRequestHeader ("header information", "header value");
        Development steps:
        1. Get the XMLHttpRequest object.
    • IE encapsulates the XMLHttpRequest into a objectxactive plug-in.
    • Firefox can create XMLHttpRequest directly.
      2. Setting state changes triggers a function.
      3. Open a link.
      4. Send the request.
      "Get Started with Ajax"
      Create XMLHttpRequest
      function Createxmlhttprequest () {
      var xmlHttp;
      try {//Firefox, Opera 8.0+, Safari
      XmlHttp = new XMLHttpRequest ();
      } catch (e) {
      try {//Internet Explorer
      XmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
      } catch (e) {
      try {
      XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
      } catch (e) {
      }
      }
      }
      return xmlHttp;
      }
      Code for Ajax:
      function LoadData () {
      1. Creating an asynchronous XMLHttpRequest Object
      var xhr = Createxmlhttprequest ();
      2. Setting state changes triggers a function
      Xhr.onreadystatechange = function () {
      callback function.
      if (xhr.readystate = = 4) {//Request send complete
      if (Xhr.status = = 200) {//response is also correct
      var data = Xhr.responsetext;
      document.getElementById ("D1"). Innerhtml=data;
      }
      }
      }
      3. Open a connection:
      Xhr.open ("GET", "/web15/servletdemo1", true);
      4. Sending the request
      Xhr.send (NULL);
      }
      "Ajax Post-entry"
      function LoadData () {
      1. Creating an Asynchronous object
      var xhr = Createxmlhttprequest ();
      2. Set the function that triggers the state change
      Xhr.onreadystatechange = function () {
      if (xhr.readystate = = 4) {
      if (Xhr.status = = 200) {
      document.getElementById ("D1"). Innerhtml=xhr.responsetext;
      }
      }
      }
      3. Open the Connection
      Xhr.open ("POST", "/web15/servletdemo2", true);
      Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
      4. Send data
      Xhr.send ("Name= John Doe &password=456");
      }
      1.2.2.2 Step Analysis:
      ? Create a user table
      ? To design a registration page:
      ? Bind an event to the User name text box: onblur
      ? Asynchronously sends a request to the servlet using Ajax in the JS function.
      ? Receive parameters in a servlet--call the business Layer--Call DAO
      n query to: User name already exists
      N not queried: User name can be used
      1.2.3 Code implementation:
Creating a User table: Create table ' user ' (' ID ' INT (one) ' NOT NULL auto_increment, ' username ' VARCHAR () DEFAULT NULL, ' password ' varch   AR (+) default NULL, ' email ' varchar (default NULL, ' name ' varchar) default null, ' sex ' varchar (TEN) default NULL, ' Birthday ' DATE default null, ' Hobby ' VARCHAR (default null, PRIMARY KEY (' id ')) engine=innodb auto_increment=6 DEF Ault charset=utf8;insert into ' user ' (' id ', ' username ', ' password ', ' email ', ' name ', ' sex ', ' birthday ', ' hobby ') VALUES (1, ' BBB ', ' 123 ', ' [email protected] ', ' Zhang San ', ' Male ', ' 1992-01-02 ', ' basketball, soccer, volleyball ', (2, ' CCC ', ' 123 ', ' [email protected] ' , ' John Doe ', ' female ', ' 1992-03-20 ', ' volleyball, table tennis '), (3, ' AAA ', ' 123 ', ' [email protected] ', ' Wangshouyi multi ', ' male ', ' 1990-08-11 ', ' Football, volleyball '), (5, ' Tom ', ' 123 ', ' [email protected] ', ' Titus ', ' Male ', NULL, ' Basketball '); Design registration page: Introduce the jar package and Tool class: Create Package Structure: Ajax asynchronous Checksum user name: function Checkusername () {//Gets the value of the text box: var username = document.getElementById ("username"). value;//Create object: var xhr = Createxmlhttprequest ();//2. State change triggers a function Xhr.onreadystatechange = functions () {if (xhr.readystate= = 4) {if (Xhr.status = = 200) {//Get to Response content: var data = xhr.responsetext;if (data = 1) {//can use document.getElementById ("S1"). InnerHTML = "<font color= ' green ' > username can be used </font>";d Ocument.getelementbyid ("Regbut"). Disabled=false; else if (data = = 2) {//already exists document.getElementById ("S1"). InnerHTML = "<font color= ' Red ' > username has been used </font>"; document.getElementById ("Regbut"). disabled=true;}}} 3. Open the Connection Xhr.open ("GET", "/web15/servletdemo3?username=" +username,true);//4. Send data xhr.send (NULL);}

1.3 Using jquery to complete the validation of an asynchronous user name: 1.3.1 Requirements:

On the registration page, when the user name is entered, the cursor leaves the text box, indicating whether the user name already exists.
If the user name already exists, it needs to be queried in the background database.
1.3.2 Analysis: 1.3.2.1 Technical Analysis:
"An overview of the Ajax part of jquery"
Because the traditional Ajax development code is troublesome, but also has the browser compatibility question. The use of traditional Ajax is minimal in the enterprise. Use some of the AJAX framework to do this.
The AJAX part of the API for jquery:

  • $ (""). Load (Url,data,function () {});
  • $.get (Url,data,function () {},datatype);
  • $.post (Url,data,function () {},datatype);
  • $.ajax ();
    use of the Ajax part of jquery
    to introduce JS for jquery.
    "Introduction to the Ajax part of jquery"
    //jquery Load Method
    $ (function () {
    ///button 1 binds a click event:
    $ ("#bt1"). Click (function () {
    $ ("#d1"). Load ("/web15/servletdemo4", {"name": "Zhang San", "Password": "123"},function (data) {
    if (data = = 1) {
    $ ( This). HTML ("Zhang San");
    }else{
    $ (this). HTML ("other");
    }
    });
    });
    });
    //Get method using jquery:
    $ (function () {
    $ ("#bt2"). Click (function () {
    $.get ("/web15/servletdemo4", {"Name": " John Doe "," Password ":" 345 "},function (data) {
    $ (" #d2 "). HTML (data);
    });
    });
    });
    //Use the Post method of jquery:
    $ (function () {
    $ ("#bt3"). Click (function () {
    $.post ("/web15/servletdemo4", {"Name" : "Harry", "Password": "456"},function (data) {
    $ ("#d3"). HTML (data);
    });
    });
    });
    //Ajax method using jquery:
    $ (function () {
    $ ("#bt4"). Click (function () {
    $.ajax ({
    Type: "Post",
    URL: "/ Web15/servletdemo4 ",
    Data:" name=aaa&password=123 ",
    success:function (data) {
    $ (" #d4 "). HTML (data);
    }

            });});

    });
    1.3.3 Code implementation:

$(function(){// 给用户名的文本框绑定一个事件:$("#username").blur(function(){// 获得文本框的值:document.getELementById().value;var username = $(this).val();// 使用jquery的ajax的操作异步发送请求.$.post("/WEB15/ServletDemo3",{"username":username},function(data){if(data==1){// 用户名可以使用$("#s1").html("<font color=‘green‘>用户名可以使用</font>");$("#regBut").prop("disabled",false);}else if(data==2){// 用户名已经存在$("#s1").html("<font color=‘red‘>用户名已经被占用</font>");$("#regBut").prop("disabled",true);}});});});

1.4 Case Three: using jquery to complete imitation Baidu information tip: 1.4.1 Demand:
On a search page, the keyboard enters some information and gives some hints (which need to be queried from the server side) below the text box.

1.4.2 Analysis: 1.4.2.1 Step Analysis:
? Create a database and a table:
? Design a page
? The text box binds an event. KeyUp
? In the KeyUp trigger function:
N Gets the value of the text box.
N asynchronously submits this value to the server. $.post ();
N commits to the servlet:
U Receive parameters:
U Call the business layer--call dao:select * from. Where xx like?;
U query after the page jumps to show the data in a table.
1.4.3 Code implementation:

To create a database and table:
CREATE TABLE Words (
ID INT PRIMARY KEY auto_increment,
Word VARCHAR (20)
);

To design a page:
<center><center><input type= "text" name= "word" id= "word" style= "width:300px"/><input type= "button" value= " Dark Horse "><center>
<div id= "D1" style= "display:none;position:absolute;top:110px;left:494px;border:1px solid blue;width:300px; height:200px; " ></div>

To bind an event to a text box: writing jquery code
$ (function () {
To bind an event to a text box:
$ ("#word"). KeyUp (function () {
Get the value of the text box:
var val = $ (this). Val ();
if (val! = "") {
Asynchronously submits this value to the server:
$.post ("/web15/servletdemo5", {"Val": Val},function (data) {
$ ("#d1"). Show ();
$ ("#d1"). HTML (data);
});
}else{
$ ("#d1"). Hide ();
}
});
});
1.5 using jquery to complete a city-City linkage case: Using XML as the response content: 1.5.1 Requirements:

Complete the effect of provincial and municipal linkage. The city's information is available from the backend server side. This functionality is used through AJAX!!!
1.5.2 Analysis: 1.5.2.1 Technical Analysis:
"XML as Response text"
list<city> list = new arraylist<city> ();
List.add (New City (1, "Harbin"));
List.add (New City (2, "Qiqihar"));
List.add (New City (3, "Mudanjiang"));
To transfer the list collection out of XML:
<list>
<city>
<name> Harbin </name>
</city>
...
</list>
Use the XStream tool: To convert a Java object to XML.
"Overview of XStream"
XStream is a oxmapping technology that is used to process XML file serialization framework, when the JavaBean serialization, or the XML file is deserialized, no other auxiliary classes and mapping files, so that XML serialization is no longer cumbersome. Br/> "Getting Started with XStream"
To introduce the jar package required by XStream:
! [] (http://i2.51cto.com/images/blog/201804/14/feb7d29950f81fe87fd9078cf9476ecc.png?x-oss-process=image/ watermark,size_16,text_qduxq1rp5y2a5a6i,color_ffffff,t_100,g_se,x_10,y_10,shadow_90,type_zmfuz3pozw5nagvpdgk=)
Entry:
@Test
list<city> list = new arraylist<city> ();
List.add (New City (1, "Harbin"));
List.add (New City (2, "Qiqihar"));
List.add (New City (3, "Mudanjiang"));

            XStream stream = new XStream();            // 设置标签的别名:            stream.alias("city", City.class);            // 设置子标签作为属性进行显示:            stream.useAttributeFor(City.class, "id");            String xml = stream.toXML(list);            System.out.println(xml);    }

1.5.2.2 Step Analysis:
? Design page:
? To bind an event to the first drop-down list: change
? In the function triggered by the Change event: submits the data to the servlet.
? In the servlet:
N Receive data: Receives the information of the submitted province.
N map<string,list<city>>
N turns the collection into XML and writes the XML back to the browser.
? Get information about the city in the XML in the callback function.
? Generates an OPTION element that adds the option element to the second drop-down list.
1.5.3 Code implementation:

  Design a page: 

1.6 Use of jquery to complete the case of provincial and municipal linkage: using JSON as the response data: 1.6.1 Requirements:

Complete the effect of provincial and municipal linkage. The city's information is available from the backend server side. This functionality is used through AJAX!!!
1.6.2 Analysis: 1.6.2.1 Technical Analysis:
"Overview of JSON"
The concept of JSON:

Examples of JSON:

    • {Key:value,key:value}
      • {ID:1,NAME:AAA}
    • [{Key:value,key:value},{key:value,key:value}]
      • [{ID:1,NAME:AAA},{ID:2,NAME:BBB}]
        To turn an object into JSON:
        Use Jsonlib to turn objects or collections in Java into JSON.
    • Jsonarray: Turns the array or list collection into JSON.
    • Jsonobject: Turns the object or map collection into JSON.

15th Chapter Web15-ajax and jquery Cases

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.