使用 AJAX 和 spring MVC,如何从 Spring Controller 返回对象列表并使用 Jquery 显示它们。
在下面发出 Ajax 请求:
$.ajax({
type: "POST",
url: "allUser.html",
dataType:'json',
data: "select=" + selectedCheckboxArray,
success: function(data){
var userListContent="";
var json =data.message;
$.each(json, function(i, obj) {
userListContent=userListContent+"<tr>";
userListContent=userListContent+"<td><input type='checkbox' value='"+obj.id+"' id='select' name='select'/></td> ";
userListContent=userListContent+"<td id='NameColumn'>"+obj.firstName+" "+obj.lastName +"</td>";
userListContent=userListContent+"<td id='genderColumn'>"+ obj.gender +"</td>";
userListContent=userListContent+"<td id='userNameColumn'>"+ obj.userName +" </td>";
userListContent=userListContent+"<td id='userTypeColumn'> "+ obj.userType +"</td>";
userListContent=userListContent+"<td id='statusColumn'>"+ obj.status +"</td>";
userListContent=userListContent+"<td id='emailIdColumn'>"+ obj.emailId +"</td>";
userListContent=userListContent+"<td id='addressColumn'>"+ obj.address +"</td>";
userListContent=userListContent+"<td id='contactnoColumn'>"+ obj.contactNo +"</td>";
userListContent=userListContent+"</tr>";
});
$('#rounded-corner tbody').html(userListContent);
//console.log(userListContent);
},
error: function(e){
alert('Error: ' + e.responseText);
}
});
MVC 控制器
@RequestMapping(value="/deleteUser",method= RequestMethod.POST)
public @ResponseBody Map<String, Object> deleteUser(UserDetails user,HttpServletRequest request,HttpServletResponse response )throws ServletException,IOException
{
System.out.println("Ajax Request Received for delete User...............");
Map<String, Object> model = new HashMap<String, Object>();
JsonResponse js=new JsonResponse();
js.setResult("pass");
js.setStatus("active");
// String operation=request.getParameter("operation");
String[] selectedUserIdParameter = request.getParameterValues("select");
System.out.println("Length:"+selectedUserIdParameter.length);
/* Code Description:
* Array "selectedUserIdParameter" above has ID like {1,2,3,.....},
* we need to use array like {1 2 3 4 } without (,).so first we must convert.
* Following code doing the same.
* After Conversion Array "selectedUserId" will have ID like {1 2 3 4 }
* If You Know PHP explode()" function ,following is doing something like what explode() function does .
*/
String msg="hello";
List<UserDetails> usersList = userService.getAllUser();
int no=usersList.size();
System.out.println("Size:"+no);
model.put("message", usersList);
model.put("jso", js);
return model;
}