Java backend development - Ajax, jQuery and JSON

Java backend development - Ajax, jQuery and JSON

Overview

The full name of Ajax is Asynchronous Javascript and XML, which is asynchronous JavaScript and XML. Ajax is a Web application technology that uses JavaScript, DOM, and servers to enable the browser to send asynchronous requests to the server.

The Ajax asynchronous request method does not send a request to the server. It will update the page after getting the data (modify the page content through DOM operations). There will be no page jump or refresh operation in the whole process.
Insert image description here
The difference between traditional request method and Ajax asynchronous request method
Insert image description here
Insert image description here
Insert image description here

Ajax multiplication table

1. Create the page mul99ajax.html and add num, button and result tags

<h3>乘法口诀表</h3>
阶数:<input type="text" id="num"/>
<input  type="button" value="提交" onclick="doAjax()"/>
<div id="result"></div>

Insert image description here
2. Add Ajax JS code

<script type="text/javascript">
function doAjax(){
    
    
   var num = document.getElementById("num").value;
   var result = document.getElementById("result");
   var xhr = new XMLHttpRequest();    
   xhr.open('get', '/myspringmvc/calAjax?num='+num);      
   xhr.send();                         
   xhr.onreadystatechange = function () {
    
    
      if (xhr.readyState === 4 && xhr.status === 200) {
    
    
	result.innerHTML =xhr.responseText;
      }
   }
}
</script>

Insert image description here
1) DOM search element num and result tag

   var num = document.getElementById("num").value;
   var result = document.getElementById("result");

Insert image description here
2) Create XHR object

 var xhr = new XMLHttpRequest();    

3) Send request

xhr.open('get', '/myspringmvc/calAjax?num='+num);      
xhr.send();    

4) Set the callback function

xhr.onreadystatechange = function () {
    
    
      if (xhr.readyState === 4 && xhr.status === 200) {
    
    
	result.innerHTML =xhr.responseText;
      }
   }

Insert image description here
5) Process asynchronous data and update data to result tag

result.innerHTML =xhr.responseText;

3. Write the back-end SpringMVC code MultitableController.java, add the annotation @ResponseBody to the processing method, and the return value is the content.

@Controller
public class MultableController {
    
    
	@RequestMapping("/calAjax")
	@ResponseBody           // 返回内容,不是JSP页面
	public String cal(Integer num) {
    
    
		Multable m=new Multable();
		m.setNum(num);
		String result=m.print();
		return result;
	}
}

Insert image description here
Insert image description here
Insert image description here
jQuery implements different colors for odd and even rows in tables
1. Create the page jQuery.html, add table tags and test data

   <table id="tb1">
        <thead>
            <th style="width: 70px;"></th>
            <th style="width: 90px;">姓名</th>
            <th style="width: 90px;">性别</th>
            <th style="width: 200px;">暂住地</th>
        </thead>
		<!-- 把表格放在thead页眉中  这一行不是数据不改变颜色 -->
        <tbody>
            <tr id="tr1">
                <td><input type="radio"  id="rd"></td>
                <td>张三</td>
                <td></td>
                <td>四川成都</td>
            </tr>
            <tr id="tr2">
                <td><input type="radio"  id="rd"></td>
                <td>李四</td>
                <td></td>
                <td>四川绵阳</td>
            </tr>
            <tr id="tr3">
                <td><input type="radio"  id="rd"></td>
                <td>王五</td>
                <td></td>
                <td>四川南充</td>
            </tr>
            <tr id="tr4">
                <td><input type="radio"  id="rd"></td>
                <td>赵六</td>
                <td></td>
                <td>四川自贡</td>
            </tr>
            <tr id="tr5">
                <td><input type="radio"  id="rd"></td>
                <td>陈勇</td>
                <td></td>
                <td>四川德阳</td>
            </tr>
            <tr id="tr6">
                <td><input type="radio"  id="rd"></td>
                <td>罗梅</td>
                <td></td>
                <td>四川宜宾</td>
            </tr>
        </tbody>
    </table>

2. Set CSS style, odd and even rows have different colors

3. Write jQuery code to set different colors for odd and even rows, and set click to change the color.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<style>
.even {
      
      
background-color: #FFF38F;
}
.odd {
      
      
background-color: #FFFFEE;
}
.s {
      
      
background-color: #FF6500;
}
/* 选中的样式只能放在后面,才能掩盖原来的样式 */
table {
      
      
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
th,
td {
      
      
border: 1px solid black;
padding: 5px;
}
</style>


<body>
<!-- 引入jquery库 -->
<script src="./js/jquery-3.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
      
      
$("tbody>tr:odd").addClass("odd");
$("tbody>tr:even").addClass("even");
$("tbody>tr").click(function() {
      
       $(this).addClass("s").siblings().removeClass("s").end().find(":radio").attr("checked", true);
});
});
</script>


<table id="tb1">
<thead>
<th style="width: 70px;"></th>
<th style="width: 90px;">姓名</th>
<th style="width: 90px;">性别</th>
<th style="width: 200px;">暂住地</th>
</thead>
<!-- 把表格放在thead页眉中 这一行不是数据不改变颜色 -->
<tbody>
<tr id="tr1">
<td><input type="radio" id="rd"></td>
<td>张三</td>
<td></td>
<td>四川成都</td>
</tr>
<tr id="tr2">
<td><input type="radio" id="rd"></td>
<td>李四</td>
<td></td>
<td>四川绵阳</td>
</tr>
<tr id="tr3">
<td><input type="radio" id="rd"></td>
<td>王五</td>
<td></td>
<td>四川南充</td>
</tr>
<tr id="tr4">
<td><input type="radio" id="rd"></td>
<td>赵六</td>
<td></td>
<td>四川自贡</td>
</tr>
<tr id="tr5">
<td><input type="radio" id="rd"></td>
<td>陈勇</td>
<td></td>
<td>四川德阳</td>
</tr>
<tr id="tr6">
<td><input type="radio" id="rd"></td>
<td>罗梅</td>
<td></td>
<td>四川宜宾</td>
</tr>
</tbody>
</table>


</body>
</html>

Insert image description here
Insert image description here

jQuery version of multiplication formula

1. In the created page mul99jquery.html, add num, button and result tags

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>乘法口诀表</h3>
阶数:<input type="text" id="num"/>
<input id="btn" type="button" value="提交"/>
<div id="result"></div>

</body>
</html>

Insert image description here
2. Add jQuery Ajax JS code

<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
      
      
	$('#btn').click(function(){
      
      
		var num=$('#num').val();
		$.ajax({
      
      
			url: '/myspringmvc/calAjax?num='+num,
			type: 'get',
			success: function(data){
      
      
				$('#result').html(data);
			}
		})
	})
})
</script>

Insert image description here
1) In the jQuery page function, add event code to the button

$(document).ready(function(){
    
    
	$('#btn').click(function(){
    
    
		var num=$('#num').val();
		$.ajax({
    
    
			url: '/myspringmvc/calAjax',
			type: 'post',
			data:{
    
    num:num},
			success: function(data){
    
    
				$('#result').html(data);
			}
		})
	})
})   

2) Get the value of the num control
var num= KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲num').val(); 3)… .ajax() function, set url, type and success functions.

$.ajax({
    
    
			url: '/myspringmvc/calAjax',
			type: 'post',
			data:{
    
    num:num},
			success: function(data){
    
    
				$('#result').html(data);
			}

3. Test
Insert image description here
test results
Insert image description here
Product type Ajax loading
1. Create a type table and enter the tested product type data

CREATE TABLE `type` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4;

Insert data

INSERT INTO `type` VALUES ('1', '零食');
INSERT INTO `type` VALUES ('2', '饮料');
INSERT INTO `type` VALUES ('3', '香烟');
INSERT INTO `type` VALUES ('7', '文具');
INSERT INTO `type` VALUES ('8', '猕猴桃');
INSERT INTO `type` VALUES ('10', '蛋糕');
INSERT INTO `type` VALUES ('11', '哈皮');
INSERT INTO `type` VALUES ('12', '芒果');
INSERT INTO `type` VALUES ('15', '果子');
INSERT INTO `type` VALUES ('16', '果子');
INSERT INTO `type` VALUES ('17', '果子');

After refreshing, as shown in Figure
Insert image description here
2. Add Javabean class Type.java and Dao class TypeDao.java

package com.javaweb.bean;


public class Type {
    
    
private Integer id;
private String name;
public Integer getId() {
    
    
return id;
}
public void setId(Integer id) {
    
    
this.id = id;
}
public String getName() {
    
    
return name;
}
public void setName(String name) {
    
    
this.name = name;
}
}

Insert image description here

package com.javaweb.controller;

import java.sql.SQLException;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javaweb.bean.Type;
import com.javaweb.dao.TypeDao;

@Controller
@RequestMapping("/type")
public class TypeController {
    
    
	private TypeDao typeDao=new TypeDao();
	@GetMapping("/find")
	@ResponseBody
	public List<Type> find(){
    
    
		try {
    
    
			return typeDao.find();
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}
		return null;
	}
}

Insert image description here
3. Modify good_add.jsp, add jQuery code, and render the type list

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<script
src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    
    
$.getJSON('/myspringmvc/type/find', function(data) {
    
    
var html='';
data.forEach(function(type){
    
    
html+='<option value="'+type.id+'">'+type.name+'</option>'
}) ;
$('#type').append(html);
});
})
</script>

<div class="form-group">
<label for="select_topic" class="col-sm-1 control-label">类目</label>
<div class="col-sm-6">
<select class="form-control" id="type" name="type_id">
</select>
</div>
</div>

</body>
</html>

Insert image description here
4. Preview the product addition form and view the type list
Insert image description here
Insert image description here
5. Modify good_edit.jsp, add jQuery code, and select the rendering type list

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.css" />
</head>
<body>
<script 
src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    
    
$.getJSON('/myspringmvc/type/find', function(data) {
    
    
var typeId=${
    
    g.type_id}
var html='';
data.forEach(function(type){
    
    
if(type.id==typeId)
html+='<option selected="selected" value="'+type.id+'">'+type.name+'</option>';
else
html+='<option value="'+type.id+'">'+type.name+'</option>';
}) ;
$('#type').append(html);
});
})
</script>

<div class="container-fluid">
<h3>修改商品页面</h3>
<br><br>
<form class="form-horizontal" action="${pageContext.request.contextPath}/goods/update" method="post">
<input type="hidden" name="id" value="${g.id }"/> 
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">名称</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" name="name" value="${g.name }" required="required">
</div>
</div>
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">价格</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" value="${g.price }" name="price" >
</div>
</div>
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">介绍</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" value="${g.intro }" name="intro" >
</div>
</div>
<div class="form-group">
<label for="input_name" class="col-sm-1 control-label">库存</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="input_name" name="stock" value="${g.stock }">
</div>
</div>
<div class="form-group">
<label for="input_file" class="col-sm-1 control-label">封面图片</label>
<div class="col-sm-6">
<input type="text" name="cover" id="input_file" value="${g.cover }" required="required">推荐尺寸: 500 * 500
</div>
</div>
<div class="form-group">
<label for="input_file" class="col-sm-1 control-label">详情图片1</label>
<div class="col-sm-6">
<input type="text" name="image1" id="input_file" value="${g.image1 }" required="required">推荐尺寸: 500 * 500
</div>
</div>
<div class="form-group">
<label for="input_file" class="col-sm-1 control-label">详情图片2</label>
<div class="col-sm-6">
<input type="text" name="image2" id="input_file" value="${g.image2 }" required="required">推荐尺寸: 500 * 500
</div>
</div>
<div class="form-group">
<label for="select_topic" class="col-sm-1 control-label">类目</label>
<div class="col-sm-6">
<select class="form-control" id="type" name="type_id">
</select>
</div>
</div>

<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<button type="submit" class="btn btn-success">提交保存</button>
</div>
</div>
</form>
</div>
</body>
</html>

6. Preview the product editing form, view the type list and select
Insert image description here

The above items have been packaged and uploaded to the network disk, and you can pick them up if needed. Attached link: https://pan.baidu.com/s/1HmVI00L_C7Zx3bqTEqzXnA?pwd=2024

If I have time and energy later, I will share more high-quality content about the field of big data. Thank you for your likes and support!

Guess you like

Origin blog.csdn.net/Myx74270512/article/details/135379699