springmvc經過ajax異步請求返回json格式數據

jspjavascript

首先建立index.jsp頁面java

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

 

controllerajax

上面index.jsp發送list請求,接下來是處理請求的controllerjson

@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.xmlapp

<mapper namespace="com.ssm.mapper.UserMapper">
    <!-- 查詢全部用戶-->
    <select id="list" resultType="com.ssm.entity.User">
        select * from user
    </select>

</mapper>

Userjsp

public class User {
    private Integer userid;
    private String username;
    private String password;
}
相關文章
相關標籤/搜索