前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>json前后入库的测试代码</title>
<script>
function ajax5()//函数google
{
//获取到到表单数据,组装成对对象
let name=document.querySelector(".name").value;
let age=document.querySelector(".age").value;
//入库,将数据获取到封装起来
let data={
name:name,
age:age
}
//前端将data对象序列化后端, encodeURIComponent(),将json对象进行编码
let stingfy = encodeURIComponent(JSON.stringify(data));
// 创建ajax对象
let xmlHttpRequest = new XMLHttpRequest();
// 配置后端请求类型 get的方式或者post true异步请求数据
xmlHttpRequest.open("get", "/hotwed_war_exploded/ajax5?stingfy="+stingfy, true);
// 监听数据是否请求成功
xmlHttpRequest.onreadystatechange = function () {
// 服务器和客户端握手
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)//服务器解析成功
{
if (xmlHttpRequest.responseText="success")
{
alert("数据入库成功")
}
}
}
//发送请求
xmlHttpRequest.send();
}
</script>
</head>
<!--<body onload="ajax5()">用于提前加载数据-->
<body>
<div id="show" style="border: solid 3px red;width: 500px;height: 100px;background: lightblue;">
姓名:<input type="text" class="name"><br>
年龄:<input type="text" class="age"><br>
<button onclick="ajax5()">提交</button>
</div>
</body>
</html>
后端代码
package Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import model.stu;
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.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
@WebServlet("/ajax5")
public class ajax5 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charest=utf-8");
// 传回前端是健和值的形式
// 后端以JSON的形式返回前端
resp.setContentType("application/json");
resp.setCharacterEncoding("utf-8");
//获取jeson格式的字符串
String datajson = req.getParameter("stingfy");
System.out.println("字符串JSON的datajson = " + datajson);
// 字符串形式改为JSON对象格式
JSONObject jsonObject = JSON.parseObject(datajson.toString());
// 获取各个属性的值
String name = jsonObject.getString("name");
String age = jsonObject.getString("age");
// 数据输出
System.out.println("name = " + name);
System.out.println("age = " + age);
// 响应用户请求时,告知用户的请求编码
PrintWriter writer = resp.getWriter();
writer.write("success");
// 释放缓存和对象
writer.flush();
writer.close();
}
}