嗨,我正在使用 spring MVC..我想在从 controleer 传递一些值时向用户发出一些警报。
这是我的 Controller 部分:
@RequestMapping(value="/deleteTeam", method=RequestMethod.POST)
public String editDeleteRecodes(@ModelAttribute NewTeams newTeams, Map<String, Object> map){
Teams teams = new Teams();
teams.setTeamID(newTeams.getTeamID());
try{
teamService.delete(teams);
}catch (DataIntegrityViolationException ex){
map.put("error", "x");
//System.out.println("aaaaa");
}
return "redirect:/";
}
这是jsp中的前端
<script type="text/javascript" >
function doAjaxPostTeamDelete (team_ID){
//get the values
//var team_ID = $('#teamID').val();
$.ajax({
type: "POST",
url: "/controller/deleteTeam",
data: "teamID=" + team_ID,
success: function(response){
// we have the response
if(x="${error}"){
alert("You Cant Delete");
}
},
error: function(e){
alert('Error: ' + e);
}
});
}
只是我想如何从 map 获取数据到jsp
最佳答案
由于您希望在成功删除时进行重定向,而不是在删除不成功时进行重定向,因此您可以在 AJAX 响应中处理重定向吗?
例如,基于马克的回答:
@RequestMapping(value="/deleteTeam", method=RequestMethod.POST)
public @ResponseBody String editDeleteRecodes(@RequestParam("teamID") String teamID) {
Teams teams = new Teams();
teams.setTeamID(newTeams.getTeamID());
String result;
try {
teamService.delete(teams);
result = "{deleted: true}";
} catch (DataIntegrityViolationException ex){
result = "{deleted: false}";
}
return result;
}
然后询问 JQuery 中的响应以确定是否重定向:
$.ajax({
type: "POST",
url: "/controller/deleteTeam",
data: "teamID=" + team_ID,
success: function(response){
// we have the response
if (response.deleted)
window.location.replace("/"); // Do the redirect
} else {
alert("You can't delete");
}},
error: function(e){
alert('Error: ' + e);
}
});
您可能需要在 Javascript 中使用重定向 URL,因为它可能需要 web 应用程序名称 - 例如。 window.location.replace("/yourWebApp/");
关于java - 使用 map 时如何从 Controller 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20064822/