在Controller的ajax方法上添加@ResponseBody

@ResopnseBody作用:

1.把java字符串转换为json

       @RequestMapping("Ajax1")

       @ResponseBody

       public String ajax(String name) {

              System.out.println(name);

              return "zs";

       }

和jsp

<%@ page language="java" contentType="text/html; charset=utf-8"

    pageEncoding="utf-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>ajax</title>

<script type="text/javascript" src="/SpringMVC/js/jquery-3.2.1.min.js"></script>

</head>

<body>

 

</body>

<script type="text/javascript">

      $.ajax({

              type:"post",

              url:"/SpringMVC/user/Ajax1",

              data:"name=李四",

              dataType:"html",

              async:"true",

              success:function(data){

                     alert(data);

              }

       });

/*    $.post("/SpringMVC/user/Ajax1",{"name":"张三"},function(data){

              alert(data);

       }); */

</script>

</html>

 

2.把java对象转化为json对象(需要导jar包:jackson)

       @RequestMapping("Ajax2")

       @ResponseBody

       public User ajax2(User user) {

              System.out.println(user);

              return user;

       }

和jsp

<script type="text/javascript">

      $.ajax({

              type:"post",

              url:"/SpringMVC/user/Ajax2",

              data:"name=张五",

              dataType:"json",

              async:"true",

              success:function(data){

                     alert(data.name);

              }

       });

/*    $.post("/SpringMVC/user/Ajax1",{"name":"张三"},function(data){

              alert(data);

       }); */

</script>

posted on 2019-09-03 22:03  kfsrex  阅读(263)  评论(0编辑  收藏  举报