ajax中的data该怎们写

前端json与java交互


<%--
  Created by IntelliJ IDEA.
  User: Gavin
  Date: 2021/12/21
  Time: 11:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transition//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
    <meta http-equiv="Content-Type" content="text/html ;charset=UTF-8">
    <title>json数据交互</title>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/static/js/jquery.min.js">

    </script>
    <script type="text/javascript">
        var pwd;
        var name;

        function testJson() {
            // var name =document.getElementById("loginName")

            pwd = $("#pwd").val();
            name = $("#name").val();
             // alert("你好" + name + pwd)这里可以弹窗,但是到了下面为什么就不好使了
            $.ajax({
                    url: "${pageContext.request.contextPath}/testJson.do",
                    type: "POST",
                 // data: '{"name":"hello","pwd":"world"}',
                   data: JSON.stringify({name:name,pwd:pwd}),
                    contentType: "application/json charset=UTF-8",
                    dataType: "json",
                    success: function (data) {
                        if (data != null) {
                            alert(data.name + "和" + data.pwd);
                        }
                    }
                }
            );

        }

        function test() {
            alert("你好")
        }

    </script>
</head>

<body>

<form method="get">
    账号:<input type="text" name="name" id="name" placeholder="请输入账号"/><br>

    密码:<input type="password" name="pwd" id="pwd" placeholder="请输入密码"/><br>
    <input type="submit" value="提交" onclick="testJson()"/><br>
</form>


</body>
</html>


@Controller
public class userController {

@RequestMapping("/testJson.do")//这里映射加上
   @ResponseBody//先测试一下如果是简单的类型
    public void testJs(@RequestBody String name,@RequestBody String pwd){
        System.out.println(name+pwd);
        //return user;
    }

打印下data是什么

<form method="get" onclick="return false">


data:JSON.stringify({"参数一":"参数值55","参数二":"来了"}) 字符串形式:参数和参数值要加 ""(双引号) ,如果参数值是变量的话,不需要加 ""(双引号)。