Catalog
Foreword --- Keep refueling and strive to accomplish the tasks of the day!
Ajax asynchronous interaction
What is AJax
Asynchronous Javascript And XML (Asynchronous Javascript And XML)
It's not new technology, it's just the integration of existing technology.
1. Use CSS and XHTML to represent.
2. Use DOM model to interact and display dynamically.
3. Use XMLHttpRequest to communicate asynchronously with the server.
4. Use javascript to bind and invoke.
What role does Ajax play?
Ajax is a technology of partial page brushing. It has a good user experience and low server pressure.
Traditional user interaction is the whole page refresh, server pressure, user experience is not good
Use AJAX asynchronous interaction when making requests and trying to receive data processing
Ajax Principle Implementation --> Implemented with js Code
<script type="text/javascript"> function loadName(){ var xmlHttp; if(window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest(); }else{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.onreadystatechange=function(){ //alert(xmlHttp.readyState+" "+xmlHttp.status); if(xmlHttp.readyState==4 && xmlHttp.status==200){ alert(xmlHttp.responseText); } } xmlHttp.open("get","getAjaxName",true); xmlHttp.send(); //Send the request to the server } </script>
Analytical Knowledge Points (get and post submission)
- XMLHttpRequest object:
- At the core of Ajax asynchronous interaction, browsers like IE7 and above now have built-in XMLHttpRequest objects.
- Older versions of IE5 IE6 use new ActiveXObject("Microsoft.XMLHTTP") objects
- xmlHttp.onreadystatechange event:
- When requests are sent to the server, we need to perform some response-based tasks.
- This event monitors our request status readyState (0-4), which is triggered whenever the state changes.
- Provides that the event is the method invoked to trigger the event when the request is ready to respond.
- The response ready value is that the status code readyState equals 4 & status equals 200
attribute | describe |
---|---|
onreadystatechange | Storage function (or function name) is called whenever the readyState property changes. |
readyState | The state of XMLHttpRequest exists. Change from 0 to 4. 0: Request uninitialized 1: Server connection established 2: Request received 3: Request processed 4: Request completed and response ready |
status | 200:'OK','404': No page found |
- xmlHttp.open(method,url,async)
Specify the type of request, the URL, and whether the request is processed asynchronously.
method: Use get or post requests
url: The requested address
async: true / false true denotes asynchronous requests and false denotes synchronous requests
- xmlHttp.send(string)
Submit data to the server
string: For post requests only
- If you need POST data like HTML forms, use setRequestHeader() to add HTTP headers. Then, in the send() method, specify the data you want to send:
<script> //2. Sending requests request.open( "POST", "/day16/DemoServlet01", true ); //If you don't have data, just write this line. request.send(); //If you want to bring data, write the following two lines //If you use the post mode with data, add a header to indicate that the submitted data type is a url-encoded form data request.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //Past with data, write form data in send method. request.send("name=aobama&age=19"); </script>
Corresponding case: Ajax username validation
- Case preparation
To query the existence of a database user, use the database
- Use of database connection pool c3p0
- Using jdbcUtils to simplify crud's JDBCUtils tool class
This is a place to query database tips, count() aggregation function, implementation of the ScalaHeader class - jar package connecting database
Demand:
- When the user name loses focus, judge, query the database whether the user name exists, and return to the page data, there is no return 0, there is return 1.
- Make a judgment on the page and add data to the element. Username exists or username is available
- code implementation
- jiaoyan.jsp front-end page
<script type="text/javascript"> function cc() { var xmlHttp; if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); }else { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.onreadystatechange = function (){ //We specify that when the response is ready to execute this method, the response is ready: readyState = 200, status = 200 if(xmlHttp.readyState == 4 && xmlHttp.status == 200){ //Get the corresponding data in the form of strings sent from the background var name = xmlHttp.responseText; //Determine whether the username exists if(name == 1){ //Insert data into selected elements document.getElementById("span1").innerHTML = "<font color='red'>User name already exists</font>"; }else { document.getElementById("span1").innerHTML="<font color='green'>User name available</font>"; } } } xmlHttp.open("post","UserJiaoyanServlet",true); //If it is submitted in post mode and the data is to be passed, add a header to tell the server that this is a form data encoded by utl xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); var username = document.getElementById("name").name; var value = document.getElementById("name").value; xmlHttp.send(username+"="+value); } </script> --------------------------------------------------------------------------- <tr> <td>Full name</td> <td> <input type="text" id="name" name="username" onblur="cc()"><span id="span1"></span> </td> </tr>
- dao layer implementation code
public class UserDaoImpl implements UserDao { @Override public int findUser(String name) throws SQLException { DataSource dataSource = JDBCUtil.getDataSource(); QueryRunner queryRunner = new QueryRunner(dataSource); Long aLong = (Long) queryRunner.query("select count(*) from user where username = ?", new ScalarHandler(), name); int i = aLong.intValue(); return i; } }
User Jiaoyan Servlet. Java - --- servlet layer
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //1. Get the reference user name String username = request.getParameter("username"); //2. Query the database to see if the username already exists, return 1 exists, return 2 does not exist. UserService userService = new UserServiceImpl(); int i = userService.findUser(username); //3. Pages before the response transfer data, without redirection and server internal jump, directly input data. PrintWriter writer = response.getWriter(); //Pay attention to using println method, which can input integer type directly and receive integer type at the front end. //Instead of using write() method, it can only output to the front-end string. writer.println(i); } catch (SQLException e) { e.printStackTrace(); } }
Ajax Implementation Principle --> jQuery Implementation
js code is encapsulated to make it less code and more convenient to use. js files need to be imported. Writing Ajax in js code is too cumbersome. Use jquery directly
Analytical Knowledge Points (get & post submission & load () loading)
Three methods are commonly used:
- Get request $get(url,collback)
- Post request $post(url,collback)
- The load load() method loads data from the server and puts the returned data into the selected element.
$(selector).load(URL,data,callback);
- get request
- Syntax format: $. get(url,collback);
URL (must): the address to be accessed (if you have data, follow the URL directly, separated by?)
Collback (optional): the name of the function executed after successful access
- Example
<script type="text/javascript"> $("#btn").click(function{ $get("url",function(data,status){ data:The content of the existing request page, the data returned status:The status of a successful request(true/false) }); }); </script>
- post request
- Request grammar: $. post(url,data,collback);
URL (must): the requested address
Data (optional): The data on request can be either json data or a simple string, or a js object
Collback (optional): the name of the function executed after successful access
- Example
<script type="text/javascript"> $("#btn").click(function{ var data1 = { name:"Donald Duck", city:"Duckburg" } $post("url",data1,function(data,status){ data:The content of the existing request page, the data returned by the page status:The status of a successful request( success/false) }); }); </script>
- load() load
Load data from the server and place it in the selected element
- Syntax format $("select"). load(url,data,collback)
url: The parameters of the request
data: A key-value pair sent to the server as opposed to a request
collback: The name of the method invoked after the function has been successfully executed
The load() method is to assign the data sent by the server to the alternate elements. With text(), the method assigns
- Example
<script type="text/javascript"> $("button").click(function(){ $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){ responseTxt:The content of the result returned after the function call is successful statusTxt:The status of successful execution success xhr:Contained XMLHttpRequest object if(statusTxt=="success") alert("External content loading was successful!"); if(statusTxt=="error") alert("Error: "+xhr.status+": "+xhr.statusText); }); }); </script>
- extend
val("aa"); can only put those tags with value attributes
html("aa"); write html code
text("aa");
Actually, it is no different from html("aa"), if you want to do html style processing for this data, you can only use html()
The function of html() and text() methods in jquery can be realized by innerHTML itself in js