springmvc通过ajax异步请求返回json格式数据

jsp

首先创建index.jsp页面

<script type="text/javascript">
    $(function () {
         $("#username").click(function () {
            $.ajax({
                url: "list",//请求地址
                type: "POST",
                dataType: "json",
                success: function(data) {//data是默认的,接收前台返回的数据
                    //alert("success");    
                    $.each(data, function(index,element) {//循环
                        $("#tr").append("<th>"+element.userid+"</th>");
                        $("#tr").append("<th>"+element.username+"</th>");
                        $("#tr").append("<th>"+element.password+"</th>");  
              // alert(data[0].areaName);////alert(data.row[0].areaName);
 
                  
                    })
                }
            });
        });
</script>
</head>
<body>
    <table align="left" border="1" cellpadding="10" cellspacing="0" id="form">
        <tr>
            <th>id</th>
            <th>用户名</th>
            <th>密码</th>
        </tr>
        <tr id="tr">

  </tr>
    </table>
</body>

controller

上面index.jsp发送list请求,接下来是处理请求的controller

@Controller
public class UserController {
    private static final String NONE = null;
    //注入ProductService
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 查询所有用户
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody//返回json格式的数据
    public List<User> List(){
        List<User> list = userMapper.list();    
        return  list;
    }

}

Mapper.xml

<mapper namespace="com.ssm.mapper.UserMapper">
    <!-- 查询所有用户-->
    <select id="list" resultType="com.ssm.entity.User">
        select * from user
    </select>

</mapper>

User

public class User {
    private Integer userid;
    private String username;
    private String password;
}