• springMVC完成ajax


    在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>

  • 相关阅读:
    学习UML类图
    【转】监听器(Listener)学习
    【转】ContextLoaderListener和DispatcherServlet加载内容的区别
    个人B站+微信公众号
    如何直观形象地树状打印一棵二叉树?
    轻松手撕10大排序算法
    简单易懂的快速幂取模算法
    程序员必学:快速幂算法
    为什么Swift和Python要抛弃++--?
    JetBrains系列IDE的配色方案(IDEACLionPyCharm)
  • 原文地址:https://www.cnblogs.com/kfsrex/p/11456020.html
Copyright © 2020-2023  润新知