2014-09-13 78 views
0

我正在使用Spring-MVC并通过ajax发布数据到控制器,根据控制器的业务逻辑,我返回不同的视图。 我被卡住的地方是,我想区分控制器在jQuery中返回的是什么样的视图,因为我们无法访问jQuery中的服务器对象,所以这是创建问题。下面是我的控制器和jquery的代码,下面是 。在jquery/javascript中访问httpservletRequest属性

控制器 -

@RequestMapping(value = "/mappedUrl", method = RequestMethod.POST) 
public ModelAndView someMethod(User dummyUser, HttpServletRequest request) { 
    //Business logic here, Boolean status is returned according to it 
    if (status) { 
     return new ModelAndView("viewOne"); 
    } else { 
     request.setAttribute("info", "viewTwo"); 
     return new ModelAndView("viewTwo"); 
    } 
} 

AJAX调用 -

function submit(formId, Url) { 
    var value = $("#" + formId).serialize(); 
    $.ajax({ 
     'type' : "POST", 
     'cache' : false, 
     'contentType' : 'application/x-www-form-urlencoded; charset=UTF-8', 
     'async' : false, 
     'url' : Url, 
     'data' : value, 
     'success' : function(data) { 
      //rendering view 
     } 
    }); 
    //NEED to determine here that which view was returned 
} 

试过在控制器设置属性和jQuery的访问,但它并没有worked.Any帮助表示赞赏。谢谢。

+0

你不能从JavaScript访问您的HttpServletRequest -

之后,该字段使用如jQuery简单访问。如果你想从那里访问任何数据,你必须将其添加到响应中。 – 2014-09-13 19:38:00

回答

0

一些知识做了一个绝招来区分通过在控制器端将if part中的唯一对象设置为请求属性并将其用于通过ajax返回数据的jsp(作为隐藏字段)的视图。

if ($('#somehiddenElement').text().trim()) { 
// if that request attribute is set then code in this block runs 
} 
0

你不能在jquery或javascript中访问服务器的不同范围对象。你应该将你的响应作为json或者xml返回,并且在jquery或者javascript中使用你的结果。 Spring MVC的3拥有完美的结合与杰克逊API将对象转换成JSON

检查下面的例子

package com.mkyong.common.controller; 

import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.ResponseBody; 
import com.mkyong.common.model.Shop; 

@Controller 
@RequestMapping("/kfc/brands") 
public class JSONController { 

@RequestMapping(value="{name}", method = RequestMethod.GET) 
public @ResponseBody Shop getShopInJSON(@PathVariable String name) { 

    Shop shop = new Shop(); 
    shop.setName(name); 
    shop.setStaffName(new String[]{"mkyong1", "mkyong2"}); 

    return shop; 

    } 

} 

检查细节例如在下面的链接 http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/

+0

感谢您的回复,如果我们正在使用json数据作为响应,用户解决方案运行良好......但是我们必然会从控制器返回视图,因为我们在项目体系结构中使用视图进行查看,并且无法对其进行更改。 – 2014-09-22 07:33:23