zl程序教程

您现在的位置是:首页 >  前端

当前栏目

响应json数据之发送ajax的请求

响应AJAX数据JSONJSON 请求 发送
2023-09-27 14:19:50 时间

响应json数据之发送ajax的请求

1.在response.jsp编写如下代码:

<%--
  Created by IntelliJ IDEA.
  User: Adair
  Date: 2020/7/2 0002
  Time: 10:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>返回响应</title>
    <script src="js/jquery.min.js"></script>
    <script>
        // 页面加载,绑定单击事件
        $(function() {
            $("#btn").click(function () {
              //  alert("hello btn");
                // 发送ajax请求
                $.ajax({
                    // 编写json格式,设置属性和值
                    url:"user/testAjax",
                    contentType:"application/json;charset=UTF-8",
                    data:'{"userName":"Adair","passWord":"123456","age":30}',
                    dataType:"json",
                    type:"post",
                    success:function(){
                        // data服务器端响应的json的数据,进行解析

                    }
                });
            });
        });
    </script>
</head>
<body>
        <button id="btn">发送ajax的请求</button>
</body>
</html>

2.创建返回响应控制器类控制器类的代码如下:

package com.txw.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * 返回响应控制器类
 * @author Adair
 */
@Controller
@RequestMapping(value = "/user")
@SuppressWarnings("all")        // 注解警告信息
public class UserController {
    /**
     * 模拟异步请求响应
     */
    @RequestMapping("/testAjax")
    public void testAjax( @RequestBody String body){
        System.out.println("testAjax方法执行了...");
        System.out.println(body);
    }
}

3.使用TomCat运行结果如图:
在这里插入图片描述
4.通过浏览器访问http://localhost:8080/response.jsp结果如图所示:
在这里插入图片描述
5.点击“发送ajax的请求”的按钮不会跳转到如图所示的界面:
在这里插入图片描述
6.控制台打印结果如图所示:
在这里插入图片描述