Springmvc complete ajax function. (Jquery. $)

1. Add jackson the jar package . SpringMVC .

 

2. The method in response plus @ResponseBody: the java object into json object.

The method may return value is a string object set.

 

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//The java object into json object requires jackson jar package 
    public String Ajax (String name) { // objects 
        the System. OUT .println (name);
         return  " John Doe " ; 
    } 
    
    @RequestMapping ( " Ajax2 " ) 
    @ResponseBody 
    public List <the Users> ajax1 (String name) { 
        the System. OUT .println (name); 
        List <the Users> Users = new new the ArrayList <the Users> (); 
        the Users user1 = new new the Users ( " John Doe 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 code as follows:

 

<%@ 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>

 

 

 

If the ajax returns a string, it will be garbled.

 

1. Preparation of annotations @RequestMapping (value = "ajax", produces = { "text / html; charset = utf-8"})

@RequestMapping(value="ajax",produces = {"text/html;charset=utf-8"})

2. modify the configuration file, the code was added in the drive following

 

 (With reference by org.springframework.web.servlet.view.InternalResourceViewResolver constructor set encoding) Reference steps:

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/yufengwang/p/11456418.html