2010-09-04 68 views
0

我已经在我的JavaScript以下电话:如何处理Spring MVC(3.0)应用程序中的Ajax.Request调用?

new Ajax.Request('/orders/check_first_last/A15Z2W2', 
{asynchronous:true, evalScripts:true, 
parameters:{first:$('input_initial').value, 
last:$('input_final').value, 
order_quantity:$('input_quantity').value}}); 

我需要什么做的就是Spring MVC的(3.0)来处理呢?

回答

5
@Controller 
@RequestMapping("/orders") 
public OrderController { 

    @RequestMapping("/check_first_last/{code}") 
    @ResponseBody 
    public Result checkFirstLast(@PathVariable String code, 
     @RequestParam int first, 
     @RequestParam int last, 
     @RequestParam("order_quantity") int orderQuantity) { 

     // fetch the result 
     Result result = fetchResult(...); 
     return result; 
    } 
} 

的几点注意事项:

  • @PathVariable获取在该请求映射
  • @RequestParam{..}定义的变量equvallent到request.getParameter(..)。如果未指定值,则假定参数的名称(firstlast)。否则,从该请求获得的值(order_quantity)
  • @ResponseBody意味着你需要杰克逊或JAXB存在于类路径,和<mvc:annotation-driven>在XML配置,它会呈现与分别JSON或XML的结果。

如果你想编写HTML直接的反应,你有两个选择:

  • 变化返回类型String并返回HTML作为String变量
  • 添加HttpServletResponse response参数的方法和使用response.getWriter().write(..)方法写入响应

资源:Spring MVC documentation

+0

辉煌!如果我需要通过替换某些HTML来将响应写回页面,我可以从checkFirstLast()方法这样做吗?哦,等等,是你的意思@ResponseBody? – Bowe 2010-09-04 18:14:37

+0

@Bowe看到我的更新。 – Bozho 2010-09-04 18:19:25

+0

@Bozho:那么调用write()方法会不会产生一个全新的HTML页面,还是允许我替换现有页面上的一个元素而不刷新页面?我希望通过在checkFirstLast()方法中执行的计算更新页面上的文本元素,但不刷新页面。 – Bowe 2010-09-04 18:24:51

相关问题