[Introduction to Ajax] To achieve partial refresh of the page, the front-end and back-end interaction are indispensable technologies

foreword

Having learned jQuery before, we will continue to learn Ajax on the basis of jQuery today. If you don't know jQuery then you can go to the previous blog of this column first.

Portal: [Introduction to jQuery] Born for JavaScript, a magical technology that simplifies JavaScript operations

Although we are learning Ajax on the basis of jQuery, Ajax is very important and will be used in future web development.

Getting to know Ajax

The first thing to know is that Ajax is not a new programming language, but a创建更好更快以及交互性更强的Web应用程序的技术。

Its core effect is that it does not reload the page in the browser ( 不刷新页面) and the Web server 交换数据, that is, it can be done without the need to refresh the page 产生局部刷新的效果.

So how do we go about using Ajax?

Ajax usage process

(1) CreateXMLHttpRequest对象
(2) SendAjax请求
(3) Process服务器

Using Ajax

Create XMLHttpRequest object

XMLHttpRequestIt is used to exchange data with the server in the background and is the core of Ajax

XMLHttpRequest is not a W3C standard and is created differently by different browsers.

So when we create it, we need to create it according to the browser. The general creation format is as follows:

var xmlhttp;
if(window.XMLHttpRequest) {
    
    
//IE+,Firefox,Chrome,Opera,Safari浏览器执行代码
	xmlhttp = new XMLHttpRequest();
}else{
    
    
//IE6,IE5浏览器执行代码
	xmlhttp = new ActiveXOBject("Microsoft.XMLHTTP");
}

send ajax

To send Ajax, we first have to create an Ajax request. To create an Ajax request, we have to use the XMLHttpRequestobject we created earlier xmlhttp.

The creation syntax is as follows:

xmlhttp.open("GET/POST", "请求地址URL", true/false);

The sending syntax is as follows:

xmlhttp.send();

Handling server responses

First you have to know:

(1) xmlhttp.onreadystatechange()Events are used to monitor the execution process of Ajax.
(2) xmlhttp.readyStateThe attribute describes the current state of XMLHttpRequest.

readyState value illustrate
readyState=0 request not initialized
readyState=1 Server connection established
readyState=2 request has been received
readyState=3 request is being processed
readyState=4 Response text has been received

(3) xmlhttp.statusProperty server response code: 200-success, 404-not found...

And we generally deal with server responses to响应已被接收且服务器处理成功时才执行

The general syntax format is:

xmlhttp.onreadystatechange = function(){
    
    
//响应已被接收且服务器处理成功时才执行
	if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    
    
		//获取响应体的文本
		var t = xmlhttp.responseText;
		//对服务器结构进行处理
		...
	}
}

Use Ajax to realize news list

After knowing how to use Ajax basically, let's practice it to implement a news list.

First let's create a news class

public class News {
    
    
	private String title;
	private String date;
	private String source;
	private String content;
	
	public News() {
    
    
		
	}
	public News(String title, String date, String source, String content) {
    
    
		super();
		this.title = title;
		this.date = date;
		this.source = source;
		this.content = content;
	}
	
	public String getTitle() {
    
    
		return title;
	}
	public void setTitle(String title) {
    
    
		this.title = title;
	}
	public String getDate() {
    
    
		return date;
	}
	public void setDate(String date) {
    
    
		this.date = date;
	}
	public String getSource() {
    
    
		return source;
	}
	public void setSource(String source) {
    
    
		this.source = source;
	}
	public String getContent() {
    
    
		return content;
	}
	public void setContent(String content) {
    
    
		this.content = content;
	}
}

After creating a servlet to initialize and process the data, we finally convert the list information into JSON format and send it back as a response.

@WebServlet("/news_list")
public class NewsListServlet extends HttpServlet {
    
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		List list = new ArrayList();//创建新闻列表
		list.add(new News("TIOBE:2019全球编程语言排行榜", "2019-5-1", "TIOBE", "..."));
		list.add(new News("TIOBE:2020全球编程语言排行榜", "2020-5-1", "TIOBE", "..."));
		list.add(new News("TIOBE:2021全球编程语言排行榜", "2021-5-1", "TIOBE", "..."));
		list.add(new News("TIOBE:2022全球编程语言排行榜", "2022-5-1", "TIOBE", "..."));
		String json = JSON.toJSONString(list);
		System.out.println(json);//控制台打印
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().println(json);
	}
}

Then use Ajax in the HTML page

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div id="container">
		<script type="text/javascript">
			//1-创建对象
			var xmlhttp;
			if(window.XMLHttpRequest) {
     
     
				xmlhttp = new XMLHttpRequest();
			}else{
     
     
				xmlhttp = new ActiveXOBject("Microsoft.XMLHTTP");
			}
			//2-发送ajax请求
			xmlhttp.open("GET", "/ajax/news_list", true);
			xmlhttp.send();
			//3-处理响应
			xmlhttp.onreadystatechange = function(){
     
     
				if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
     
     
					var text = xmlhttp.responseText;
					var json = JSON.parse(text);//把响应体的文本转换为JSON格式
					var html="";
					//动态处理每一条JSON
					for(var i = 0; i < json.length; i ++) {
     
     
						var news = json[i];
						html = html + "<h1>" + news.title + "</h1>";
						html = html + "<h2>" + news.date + "&nbsp" + news.source + "</h2>";
						html = html + "<hr/>";
					}
					//为id为container的容器添加新创建的html页面
					document.getElementById("container").innerHTML = html;
				}
			}	
		</script>
	</div>
</body>
</html>

output:
insert image description here

Synchronous and Asynchronous

We create the Ajax syntax format as follows:

xmlhttp.open("GET/POST", "请求地址URL", true/false);

I don't know if you have noticed the third parameter when creating Ajax.

The first two parameters are relatively easy to understand: the request method and the request url.

But the third parameter here is trueor false, which you may not understand.

The third parameter here is to represent synchronous or asynchronous.

Asynchronous processing : It is triggered by events to ajax to request the server. 无论服务器有没有响应,客户端的其他代码一样可以运行。
Synchronous processing during this period : trigger ajax through practice, request the server, and wait for the server to process the request during this period 在这个期间客户端不能做任何处理.当 ajax 执行完毕才会继续执行其他代码。

Synchronization: submit an Ajax request -> wait for server processing -> return after processing (the client browser cannot do anything during this period)

Asynchronous: The request is triggered by an event -> processed by the server (this is that the browser can still do other things) -> processed

Synchronization needs to wait for the returned result to continue, and asynchronous does not have to wait. Generally, only the asynchronous result needs to be monitored.

Take a simple chestnut:

Synchronization means that when you ask me to go to dinner, I will go to dinner with you when I hear it; if you do not hear it, you will keep calling until I tell you that you have heard it, and then we will go to dinner together.

Asynchronous means that you call me and then go to eat by yourself. I may leave immediately after I get the news, or I may wait until I am done to eat.

Pay attention to Ajax here 一般默认true为异步. When we use it, we also use asynchronous in most cases, that is: true.

jQuery support for Ajax

The process of using Ajax that I learned before is:

(1) CreateXMLHttpRequest对象
(2) SendAjax请求
(3) Process服务器

But if you have to go through these three steps every time you use Ajax, isn't it too troublesome.

So jQuery simplified and encapsulated the use of Ajax.

Next, learn how to implement Ajax using jQuery.

jQueryThe Ajaxoperation is encapsulated, and finally only the $.ajax()method is provided to implement the Ajaxoperation.

The syntax format is:

$.ajax(options);

It should be mentioned that options is a JSON-like object. We need to set parameters in this JSON class object.

Common setting items

Common setting items illustrate
url send request address
type Request type get or post
data Parameters passed to the server
dataType Data type of server response (text/json/xml/html/jsonp/script)
success The handler function when the response is received
error The handler function when the request fails

practice strengthening

We modify the previously implemented servlet, and then use jQuery to implement Ajax.

Modifying the previous servlet, we make different responses according to the incoming parameters, and the others are the same as before.

@WebServlet("/news_list")
public class NewsListServlet extends HttpServlet {
    
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		String type = request.getParameter("t");//接收参数
		List list = new ArrayList();
		if(type != null && type.equals("pypl")) {
    
    
			list.add(new News("PYPL:2019全球编程语言排行榜", "2019-5-1", "PYPL", "..."));
			list.add(new News("PYPL:2020全球编程语言排行榜", "2020-5-1", "PYPL", "..."));
			list.add(new News("PYPL:2021全球编程语言排行榜", "2021-5-1", "PYPL", "..."));
			list.add(new News("PYPL:2022全球编程语言排行榜", "2022-5-1", "PYPL", "..."));
		}else if(type == null || type.equals("tiobe")) {
    
    
			list.add(new News("TIOBE:2019全球编程语言排行榜", "2019-5-1", "TIOBE", "..."));
			list.add(new News("TIOBE:2020全球编程语言排行榜", "2020-5-1", "TIOBE", "..."));
			list.add(new News("TIOBE:2021全球编程语言排行榜", "2021-5-1", "TIOBE", "..."));
			list.add(new News("TIOBE:2022全球编程语言排行榜", "2022-5-1", "TIOBE", "..."));
		}
		String json = JSON.toJSONString(list);
		System.out.println(json);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().println(json);
	}
}

Use jQuery to implement Ajax, here we set the parameter to pypl, and only print out the title.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.6.0.js"></script>
<script type="text/javascript">
	$(function(){
     
     
		$.ajax({
     
     
			"url" : "/ajax/news_list",
			"type" : "get",
			"data" : {
     
     "t":"pypl"},//多个参数用逗号隔开即可
			"dataType" : "json",
			"success" : function(json){
     
     
				for(var i = 0; i < json.length; i ++) {
     
     
					$("#container").append("<h1>" + json[i].title + "</h1>");
				}
			},
			"error" : function(xmlhttp, errorText){
     
     
				if(xmlhttp.status == "405"){
     
     
					alert("无效的请求方式");
				}else if(xmlhttp.status == "404"){
     
     
					alert("URL资源不存在");
				}else if(xmlhttp.status == "500"){
     
     
					alert("服务器内部产生异常,请联系管理员");
				}else{
     
     
					alert("产生异常,请联系管理员!");
				}
			}
		})
	})
</script>
</head>
<body>
	<div id ="container"></div>
</body>
</html>

output:
![Insert image description here](https://img-blog.csdnimg.cn/d876b9535300482eb22dd8dc54493394.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAX-eZveeZveS4jeeZvQ==,size_20,color_FFFFFF,

Epilogue

Although the content is relatively short, we cannot ignore the importance of Ajax. After going down, we need to practice a lot, and practice makes perfect.

This column is continuously updated…

Guess you like

Origin blog.csdn.net/apple_51673523/article/details/123478099