解决$.ajax的回调函数值和SpringMVC返回String时冲突的问题

我们靠ajax发送请求,给其success:function(result){}回调函数并根据返回的result进行下一步操作

1
2
3
4
5
6
7
8
9
10
$.ajax({
     url: "${pageContext.request.contextPath}/items/batchDelete.action" ,
     type: 'POST' ,
     data:{ "ids" :ids},
     success: function (result){
         if(result == 'success' ){
              window.location.href= "${pageContext.request.contextPath}/items/toItemsList.action" ;
         }  
     }
});
后台代码如下:

因为SpringMVC返回String时候是进行页面跳转的,如return "success"时,在配置了前缀后缀的情况下,页面会跳转到 localhost:8080/xxx/xxx/success.jsp,这时就会因为找不到页面而报404,而且ajax接收到的result是整个localhost:8080/xxx/xxx/success.jsp 的html对象

并且我们此时是ajax提交的请求,仅仅想给ajax返回一个回调函数值,根据这个返回值进行下一步操作

解决方法:此时可以添加 @ResponseBody注解即可返回给ajax给定的字符串,而不是让SpringMVC以为返回的String是要进行页面跳转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RequestMapping( "/batchDelete.action" )
@ResponseBody
public String batchDelete(String ids){
     
     String[] strs = ids.split( "," );
     
     try {
         itemsService.batchDelete(strs);
         return "success" ;
     } catch (Exception e) {
         
         e.printStackTrace();
     }
     return "error" ;
}

猜你喜欢

转载自blog.csdn.net/weixin_39214481/article/details/80655473