Springmvc完成ajax功能。(jquery. $)
Posted yufengwang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springmvc完成ajax功能。(jquery. $)相关的知识,希望对你有一定的参考价值。
1.加入jackson的jar包. springmvc。
2.在响应的方法上加上@ResponseBody :把java对象转化为json对象。
3.方法的返回值可以是对象集合字符串。
package com.zhiyou100.wyf.controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.zhiyou100.wyf.bean.Users; @Controller @RequestMapping("/ajax/") public class AjaxController @RequestMapping(value="Ajax1",produces="text/html;charset=UTF-8") @ResponseBody//把java对象转化json对象,需要使用jackson的jar包 public String ajax(String name) //对象 System.out.println(name); return "张三"; @RequestMapping("Ajax2") @ResponseBody public List<Users> ajax1(String name) System.out.println(name); List<Users> users = new ArrayList<Users>(); Users user1 = new Users("张三1",11,"男",11,"111"); Users user2 = new Users("张三2",11,"男",11,"111"); Users user3 = new Users("张三3",11,"男",11,"111"); Users user4 = new Users("张三4",11,"男",11,"111"); Users user5 = new Users("张三5",11,"男",11,"111"); Users user6 = new Users("张三6",11,"男",11,"111"); users.add(user1); users.add(user2); users.add(user3); users.add(user4); users.add(user5); users.add(user6); return users;
jsp代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="stylesheet" href="/springMvc-03/css/index.css"> <script type="text/javascript" src="/springMvc-03/js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $.post("ajax/Ajax1","name":"张三1",function(data) alert(data); ); </script> <script type="text/javascript"> $.post("ajax/Ajax2","name":"张三2",function(result) $.each(result,function(i,n) alert(n.uname) ) ); </script> </head> <body> <img src="/springMvc-03/img/32551428_1231_20190617-131828.png"> </body> </html>
如果ajax返回的为字符串,那么就会出现乱码。
1.编写注解@RequestMapping(value="ajax",produces = "text/html;charset=utf-8")
@RequestMapping(value="ajax",produces = "text/html;charset=utf-8")
2.修改配置文件,在驱动中加入代码如下
参考步骤(通过org.springframework.web.servlet.view.InternalResourceViewResolver的有参构造函数进行设置编码):
以上是关于Springmvc完成ajax功能。(jquery. $)的主要内容,如果未能解决你的问题,请参考以下文章
springmvc完成ajax功能以及返回字符串出现乱码的解决方法