servlet代码
package servlet;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
@WebServlet(urlPatterns = "/servlet/ajaxTest", description = "这里是说明")
public class ajaxTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 接收前端传的json数据
request.setCharacterEncoding("UTF-8");
String json = request.getReader().readLine();
System.out.println("接收到的json数据:" + json);
// 返回json数据
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 0);
jsonObject.put("msg", "success");
jsonObject.put("data", "这是返回的数据");
String result = jsonObject.toJSONString();
// 设置返回的json数据格式
response.setContentType("application/json;charset=UTF-8");
// 发送json数据
response.getWriter().write(result);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<!-- 设置文档类型为HTML5 -->
<meta charset="UTF-8">
<!-- 设置文档字符编码为UTF-8 -->
<title>Ajax Example</title>
<!-- 设置文档标题 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- 引入jQuery库 -->
<style>
body { font-family: Arial, sans-serif; }
/* 设置页面字体 */
</style>
</head>
<body>
<!-- 发送数据按钮 -->
<button id="sendButton">Send Data</button>
<!-- 显示结果的区域 -->
<div id="result"></div>
<!-- JavaScript代码 -->
<script>
$(document).ready(function () {
// 当DOM完全加载后执行
$("#sendButton").click(function () {
// 当点击按钮时触发
var data = {
"name": "John Doe",
"age": 30
};
// 构造要发送的JSON数据
// 发起Ajax POST请求
$.ajax({
url: "./servlet/ajaxTest", // 请求的URL地址
type: "POST", // HTTP请求类型
data: JSON.stringify(data), // 将JSON数据转换为字符串
contentType: "application/json", // 设置请求的内容类型
success: function (response) {
// 如果请求成功
$("#result").text("Received: " + JSON.stringify(response));
// 显示服务器返回的JSON数据
},
error: function (jqXHR, textStatus, errorThrown) {
// 如果请求失败
$("#result").text("Error: " + textStatus + " " + errorThrown);
// 显示错误信息
}
});
});
});
</script>
</body>
</html>