java - 使用 map 时如何从 Controller 获取数据

标签 java javascript jsp jquery spring-mvc

嗨,我正在使用 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/

相关文章:

java - ANT 找不到特定的库

javascript - 如何将其包装在 javascript 函数中?

javascript - 在运行时更改背景颜色

java - 将 TextView 文本设置为与 EditText 字段文本颜色相同的颜色

java - 饼图的事件处理

javascript - JQuery文档点击解除绑定(bind)删除所有子点击事件

javascript - 为什么页面加载时会执行 javascript?

java - 将 Controller 映射到 Spring MVC 中的绝对路径

java - 请求的列表键 'countries' 无法解析为集合/数组/映射/枚举/迭代器类型。示例 : people or people. {名称}

java - 通过正则表达式获取多个匹配项