Ajax使用例子

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值