current position:Home>Chapter 12 Ajax

Chapter 12 Ajax

2022-04-29 07:24:05wuling129

Web In development ,Ajax technology It can realize the partial update of the page , data Asynchronous interaction This way brings users a better use experience . Use JavaScript Can achieve Ajax operation , But use JavaScript Realization Ajax The operation is not only code complex , You also need to consider the compatibility of browsers , Inconvenience to developers .jQuery Yes JavaScript Secondary packaging is carried out, and Ajax The operation of has been reorganized and encapsulated , To simplify the Ajax Use . This chapter will focus on jQuery in Ajax Explain in detail the use of .

12.1 Ajax summary

Ajax The full name is Asynchronous Javascript and XML, namely asynchronous Of JavaScript and XML.

Traditional request :

Ajax Asynchronous request mode

 Ajax Do not make requests to the server in an asynchronous manner , Will get the data and then update the page ( adopt DOM Operate and modify the page content ), There will be no page Jump or refresh operation in the whole process .

  The second is more :

Comparison mode

Agreement to be followed

How the request is sent

Data presentation

The traditional way

HTTP

Page link jump issue

Reload new page

Ajax Asynchronous way

HTTP

from XMLHttpRequest Instance makes a request

JavaScript and DOM Technology updates the data to this page

12.2jQuery frame

introduce jQuery

<!--  Introduce locally downloaded jQuery -->
<script src="jquery-1.6.1.js"></script>


<!--  introduce CDN Accelerated jQuery -->
<script src="https://code.jquery.com/jquery-1.6.1.js"></script>

jQuery The methods provided can be roughly divided into Two types of , One is for sending requests $.get() Method and $.post() Method ; The other is used to obtain data in different formats $.load() Method $.getJSON() Method and $.getScript() Method .

12.2.3  jQuery Medium load() Method

load(url,data,callback)

url

It's necessary , Specify the path to load the resource

data

Optional , Data sent to the server

callback

Optional , The function executed when the request is completed

request HTML file

firstweb\WebContent\chapter12  Create under directory load.jsp,target.jsp, At the same time  jquery-3.6.0.js Put it in the directory :

target.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>target</title>
</head>
<body>
<h3> In the Quiet Night </h3>
<h6> The tang dynasty   Li Bai </h6>
<pre>
   abed, I see a silver light ,
   The frost on the ground .
   look at the bright moon ,
   Bow your head and think of your hometown .
</pre>
</body>
</html>

load.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>load</title>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/chapter12/jquery-3.6.0.js"></script>
    <!-- ${pageContext.request.contextPath} yes JSP The way to get the absolute path , Equivalent to  <%=request.getContextPath()%> .
 That is, take out the name of the deployed application or the name of the current project  -->
</head>
<body>
<button id="btn"> Load data </button>
<div id="box"></div>
<script type="text/javascript">
    $('#btn').click(function() {
        $('#box').load('http://localhost:8080/firstweb/chapter12/target.jsp');
    });
</script>
</body>
</html>

Send data to the server

establish load2.jsp file

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>load2</title>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/chapter12/jquery-3.6.0.js"></script>
</head>
<body>
<button id="btn"> Load data </button>
<div id="box"></div>
<script>
    $('#btn').click(function() {
/*        $('#box').load('http://localhost:8080/chapter12/Load2Servlet',
            {username: 'itcast', password: 123});*/
        $('#box').load('http://localhost:8080/firstweb/load2Servlet',
            {username:'itcast',password:123},            // Pay attention to the Chinese and English symbols in the source code 
            function(responseData, status, xhr){
            console.log(responseData);	//  Output the requested data 
            console.log(status);		//  Output request status 
            console.log(xhr);			//  Output XMLHttpRequest object 
        })
    });
</script>
</body>
</html>

establish The name is load2Servlet Of Servlet class , be used for receive load2.jsp Of request

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		 response.setContentType("text/html;charset=utf-8");
	     // obtain load2.jsp Page username And password value 
	     String username=request.getParameter("username");
	     String password=request.getParameter("password");
	     response.getWriter().println(" Registered successfully !<br/> user name :"+username+"<br/> password :"+password);
	        
	}

Callback function

load() Methods the first 3 The parameters are Callback function , This function is requesting data After loading perform . The callback function is used to obtain the relevant information of this request , It has 3 Default parameters , Respectively represent the response data 、 Request status and XMLHttpRequest object . among , The request status shares 5 Kind of , Respectively success( success )、notmodified( not changed )、error( error )、timeout( Overtime ) and parsererror( Parse error ).

Access in browser http://localhost:8080/firstweb/chapter12/load2.jsp, And click “ Load data Button , And on again browser Developer tools ( Generally, press... In the browser F12 The key can directly open ), The information printed on the browser console is as follows .

 jQuery Medium GET Request and POST request

$.get() Method :

$.get(url,data,function(data, status, xhr),dataType)

From the above grammar ,get() Method yes jQuery Of Static methods , from “$” Object calls directly .$.get() The parameter meanings of the method are shown in the following table .

Parameters

describe

url

must , Specify the path to load resources

data

Optional , Data sent to the server

function(data, status, xhr)

Optional , Function executed when the request is successful data Represents the data returned from the server status Indicates the status value of the request xhr Indicates the... Associated with the current request XMLHttpRequest object

dataType

Optional , The data type of the expected server response xml、html、text、script、json、jsonp

Create name as get.jsp Of JSP page , stay get.jsp Call in $.get() Method request target.jsp page , And display the returned data to the specified position on the page .

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>get</title>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/chapter12/jquery-3.6.0.js"></script>
</head>
<body>
<button id="btn"> Load data </button>
<div id="box"></div>
<script>
    $('#btn').click(function() {
        $.get('http://localhost:8080/firstweb/chapter12/target.jsp', function(data) {
            $('#box').html(data);
        }, 'html');
    });
</script>
</body>
</html>

add to get2.jsp file , Used to send data to the server .

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>get2</title>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/chapter12/jquery-3.6.0.js"></script>
</head>
<body>
<button id="btn"> Load data </button>
<div id="box"></div>
<script>
    $('#btn').click(function() {
        var userData = {username:'itcast',password:123};
/*        $.get('http://localhost:8080/firstweb/load2Servlet',userData,
            function(data) {
                $('#box').html(data);
            }, 'html'); */
            
        $.post('http://localhost:8080/firstweb/load2Servlet',userData,
            function(data) {
                $('#box').html(data);
            }, 'html'); 
    });
</script>
</body>
</html>

stay When reviewing the element, it was found that Console tip :

Added synchronous DOM mutation listener to a 'DOMNodeInsertedIntoDocument' event. Consider using MutationObserver to make the page more responsive.

  • MutationObserver interface Can be used to monitor DOM Changes in trees .
  • MutationObserver It's old DOM3 Event specification Mutation Events A replacement for the feature .
  • stay DOM When the event is triggered , Will trigger MutationObserver In the middle of callback.
  • DOM Monitoring won't start immediately , Must call observer() Method to monitor .

Remind us to use  MutationObserver. This does not affect the result , About MutationObserver For details, please refer to the blog :

MutationObserver What is it? ?

12.3JSON data format

stay Ajax In request , Most commonly used data format by JSON.JSON It's a kind of storage key/value( Key value pair ) Data Format , Be similar to JavaScript Object format for . Its advantage is that the data can be Processing into objects , Easy access to information fields .JSON The data format of is as follows .

[{
	"name": "Java Basics ",
	"author": "XX The programmer ",
	"price": "¥78.20"
}, {
	"name": "Java Advanced ",
	"author": "XX The programmer ",
	"price": "¥39.50"
}]

JSON The array data is stored in a pair of [] in , stay [] in , Each set of data uses a pair of {} Cover up , Use... Between multiple groups “,” Separate . It should be noted that , If value yes String type You must use Double quotes Lead up , If it is value yes number、object、boolean And arrays without double quotes .

The new name is Book Class :

package chapter12;

public class Book {
    private String name;  				// Title 
    private double price; 				// Price 
    private String auther; 				// author 
    
    public Book() {
		// TODO Auto-generated constructor stub
	}
    
    public Book(String name,double price,String auther) {
		// TODO Auto-generated constructor stub
    	this.name = name;
    	this.price = price;
    	this.auther = auther;
	}
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getAuther() {
        return auther;
    }
    public void setAuther(String auther) {
        this.auther = auther;
    }
}

The new name is JSONServlet Class , Used to deliver to the front page JSON data

package chapter12;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;

/**
 * Servlet implementation class JSONServlet
 */
@WebServlet("/JSONServlet")
public class JSONServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JSONServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		
		 // establish list aggregate 
        List<Book> Books= new ArrayList<Book>();
        Book  b =new Book();
        b.setName("Java Basics ");
        b.setAuther("XX The programmer ");
        b.setPrice(78.20);
        Books.add(b);
        Book  b1 =new Book();
        b1.setName("Java Advanced ");
        b1.setAuther("itcast");
        b1.setPrice(68.20);
        Books.add(b1);
        // establish JSONArray object 
        JSONArray jsonArray=JSONArray.fromObject(Books);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(jsonArray);
        out.flush();
        out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Create name as JSON Of jsp page , Used to send asynchronous requests and get JSON Formatted data .

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>JSON</title>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/chapter12/jquery-3.6.0.js"></script>
</head>
<body>
<button id="btn"> Load data </button>
<table id="dataTable" border="1" cellpadding="0" cellspacing="0">
    <tr>
        <th> author </th>
        <th> Title </th>
        <th> Price </th>
    </tr>
</table>
<script type="text/javascript">
    $('#btn').click(function() {
        $.getJSON('http://localhost:8080/firstweb/JSONServlet',
            function(data) {
                var html = '';
                for (var Book in data) {
                    html += '<tr>';
                    for (var key in data[Book]) {
                        html += '<td>' + data[Book][key] + '</td>';
                    }
                    html += '</tr>';
                }
                $('#dataTable').append(html);
            });
    });
</script>
</body>
</html>

12.4Ajax Basic operation of

Refer to the post :$.ajax() Methods,

Parameters

describe

url

Request address , The default is the current page

data

Data sent to the server

xhr

Used to create XMLHttpRequest Object function

beforeSend(xhr)

Function executed before sending the request

success(result,status,xhr)

Function executed when the request is successful

error(xhr,status,error)

The function executed when the request fails

complete(xhr,status)

The function executed when the request is completed ( When the request succeeds or fails, it will call , The order is success and error After the function )

callback

The function executed when the request is completed

dataType

The data type of the expected server response

type

Request mode (GET or POST)

cache

Whether to allow the browser to cache the requested page , The default is true

cache

Set the local request timeout ( In milliseconds )

async

Whether to use asynchronous request . The default is true

username

stay HTTP The user name used in the access authentication request

password

stay HTTP Access the password used in the authentication request

contentType

The type of content used to send data to the server . The default is “application/x-www-form-urlencoded”

ajax.jsp Write code in the page , Realization $.ajax() Method for asynchronous login

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ajax</title>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/chapter12/jquery-3.6.0.js"></script>
            
    <script type="text/javascript">
        $(document).ready(function(){
            $("button").click(function(){
                $.ajax({
                    type:"post",				// submission 
                    url:'http://localhost:8080/firstweb/AJAXServlet',
                    data:{
                        userName:  $("#userName").val(),
                        password:  $("#password").val()
                    },              			//data The content in will be automatically added to url Back 
                    dataType: "text",    		// Return the format of the data 
                    success:function(a){      	// Function to be executed after successful request 
                        if(a=="true"){
                            $('#suss').html(" Login successful !")
                        }else{
                            $('#suss').html(" Login failed !")
                        }
                    },
                    error :function () {      	// Function executed after request failure 
                        alert(" request was aborted ");
                    },
                });
            });
        });
    </script>
</head>
<body>

<div>
    <div>
        <ul>
            <li> user name :</li>
            <li><input id="userName" name="userName" type="text" /></li>
        </ul>
    </div>
    <div>
        <ul>
            <li> password :</li>
            <li><input id="password" name="password" type="password"/></li>
        </ul>
    </div>
    <div>
        <ul>
            <li><button> Sign in </button></li>
        </ul>
    </div>
    <div id="suss"></div>
</div>
</body>
</html>

Create name as AJAXServlet Of Servlet class , It is used to judge whether the account and password entered by the user are correct .

package chapter12;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AJAXServlet
 */
@WebServlet("/AJAXServlet")
public class AJAXServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AJAXServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		 boolean flag = false;
	     Map<String, String[]> parameterMap = request.getParameterMap();
	     if ((request.getParameter("userName")).equals("itcast")
	              && request.getParameter("password").equals("123")) {
	          flag = true;            // Login success flag 
	      } else {
	          flag = false;
	      }
	      response.setContentType("text/html;charset=utf-8");
	      // Use PrintWriter Method to print login results 
	      PrintWriter out = response.getWriter();
	      out.print(flag);
	      out.flush();
	      out.close();
	}

}

Mission : Real time display of announcement information

To complete a program , Application required Ajax Achieve no refresh 、 every other 10 Get the latest announcement from the database every minute , And scroll through .

The new table in the database is named info Bulletin of

/*
Navicat MySQL Data Transfer

Source Server         : 127.0.0.1
Source Server Version : 50737
Source Host           : localhost:3306
Source Database       : jdbc

Target Server Type    : MYSQL
Target Server Version : 50737
File Encoding         : 65001

Date: 2022-04-28 11:22:51
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for info
-- ----------------------------
DROP TABLE IF EXISTS `info`;
CREATE TABLE `info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(200) CHARACTER SET utf8 NOT NULL,
  `content` text CHARACTER SET utf8,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of info
-- ----------------------------
INSERT INTO `info` VALUES ('1', ' School closure notice ', '4 month 26 Friday night 8 spot , The school is closed ');
INSERT INTO `info` VALUES ('2', ' Eat well, drink well ', ' Eat well, drink well ');

establish index.jsp file , Display the relevant contents of the latest announcement in this file , Mainly used Ajax Asynchronously submit requests to regularly read the latest commodity information in the database .

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>index</title>
  <script type="text/javascript"
          src="${pageContext.request.contextPath}/chapter12/jquery-3.6.0.js"></script>
          
  <script type="text/javascript">
    function getInfo() {
      $.get("http://localhost:8080/firstweb/chapter12/getInfo.jsp?nocache=" + new  Date().getTime(),function (data) {
        $("#showInfo").html(data);
      });
    }
    $(document).ready(function () {
      getInfo();// call getInfo() Method to obtain announcement information 
      window.setInterval("getInfo()",10000);
    })
  </script>
</head>
<body>
<section>
  <marquee id="showInfo" direction="up" scrollamount="3">
  </marquee>
</section>
</body>
</html>

establish getInfo.jsp The page is used to query data from the database

<%@ page language="java" contentType="text/html;charset=UTF-8"
         pageEncoding="UTF-8" %>
         
<%@page import="java.sql.*" %>
<jsp:useBean id="conn" class="chapter12.ConnDB" scope="page"></jsp:useBean>
<ul>
    <%
        ResultSet rs=conn.executeQuery("select title from info order by id desc;");
        if(rs.next()){
            do{
                out.print("<li>"+rs.getString(1)+"</li>");
            }while (rs.next());
        }else{
            out.print("<li> No announcement information yet !</li>");
        }
    %>
</ul>

Create name as ConnDB.java Class , For interacting with a database .

package chapter12;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class ConnDB {
    public Connection conn =null;    // Statement Connection Instance of object 
    public Statement stmt = null;    // Statement Statement Instance of object 
    public ResultSet rs = null;      // Statement ResultSet Examples of objects 
    // Specify the location where the resource file is saved 
    private static String propFileName= "connDB.properties";
    // Create and instantiate Properties Instance of object 
    private static Properties prop=new Properties();
    // Define and save database driven variables 
    private static String dbClassName ="";
    private static String dbUrl="";
    private static String user="";
    private static String pass="";
    /**
     *  Construction method 
     */
    static{
        try{
        	//InputStream in =new Example02().getClass().getClassLoader().getResourceAsStream("dbcpconfig.properties");
            // take Properties File read to InputStream In the object 
            //InputStream in=ConnDB.class.getResourceAsStream(propFileName);
        	System.out.println(" Start reading resources ");
        	InputStream in=new ConnDB().getClass().getClassLoader().getResourceAsStream(propFileName);
            prop.load(in);
            dbClassName = prop.getProperty("DB_CLASS_NAME"); // Get the database driver 
            dbUrl = prop.getProperty("DB_URL");  // Get the database driver 
            user = prop.getProperty("user");  // Get the database account 
            pass = prop.getProperty("pass");  // Get database password 
            
            System.out.println(dbUrl);
        }catch (Exception e){
            e.printStackTrace();                             // Output exception information 
        }
    }
    /**
     *  Connect to database 
     */
    public  Connection getConection(){
        try{
            Class.forName(dbClassName).newInstance(); // Load the database driver 
            // Establishment and database URL Connection to the database defined in 
            conn = DriverManager.getConnection(dbUrl,user,pass);
        }catch (Exception ee){
            ee.printStackTrace();
        }
        if(conn==null){
            System.err.print(" The connection fails ");
        }
        return conn;
    }
    /**
     *  Execute the query 
     */
    public ResultSet executeQuery(String sql){
        try{
            conn=getConection();
            stmt =conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
            // perform SQL sentence , And return a ResultSet object rs
            rs =stmt.executeQuery(sql);
        }catch (SQLException ex){
            System.err.print(ex.getErrorCode());
        }
        return rs;
    }
    /**
     *  Close the connection to the database 
     */
    public void close(){
        try{
            if(rs!=null){
                rs.close();
            }
            if (stmt!=null){
                stmt.close();
            }
            if (conn!=null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

create a file connDB.properties, Used to store parameter information of database connection . Pay attention to putting the file in the resource directory , Otherwise, it cannot be read correctly .

DB_CLASS_NAME =com.mysql.cj.jdbc.Driver
DB_URL=jdbc:mysql://localhost:3306/jdbc?serverTimezone=GMT%2B8
user =root
pass =123456

copyright notice
author[wuling129],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290420384251.html

Random recommended