如何将Controller变量值写回发送Ajax请求的HTML页面而不刷新页面?

时间:2010-09-04 20:39:07

标签: java ajax spring spring-mvc

以下JavaScript

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}});

触发对checkFirstLast中的OrderController方法的Ajax调用:

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

   @RequestMapping("/check_first_last/{code}")
   @ResponseBody
   public String checkFirstLast(@PathVariable String code, 
        @RequestParam int first, 
        @RequestParam int last, 
        @RequestParam("order_quantity") int orderQuantity)  {
       Integer newResult = new Integer(last - first);
       return newResult.toString();
  }
}

如果我想将newResult方法中的checkFirstLast字符串写入发送Ajax请求的页面上的result_text HTML元素,请替换{{1}设置的值JSTL变量:

initialResult

我需要对上面的控制器方法(<h2 id="result_text"><c:out value="${initialResult}"/></h2> )进行哪些更改,现在我已经将Jackson JSON库包含在我的项目中了?

2 个答案:

答案 0 :(得分:1)

ajax中的流程是:

  1. 使用javascript向服务器发送请求
  2. 服务器上的处理请求
  3. 将回复发送回客户
  4. 使用javascript处理流程并更新页面
  5. 您提供的代码中缺少第4步。

    在我看来,你正在使用the prototype javascript framework,这是正确的吗? 如果您查看the documentation for ajax requeststhe ajax options,您会看到在成功处理请求或发生故障时可以指定回调函数。

    将您的javascript更改为:

    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
            },
            onSuccess: function(transport) 
            {
                 $('result_text').update(transport.responseText);
            }
        }
    );
    

    让我知道它给了什么。

答案 1 :(得分:1)

这是我编写的用于处理Ajax的abstract控制器。这实际上来自Struts上的DispatchAction示例。

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        AjaxResponse ajaxResponse = null;
        String parameter = "command";

        try {
            String methodName = request.getParameter(parameter);
            Method method = getMethod(methodName);

            ajaxResponse = invokeMethod(request, response, method);         
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error(e.getLocalizedMessage());
            ajaxResponse = toXmlException(e);
        }

        if (ajaxResponse != null) {
            //Finally
            response.setContentType(ajaxResponse.getContentType());
            response.setHeader("Cache-Control", "no-cache");
            OutputStream out = response.getOutputStream();
            out.write(ajaxResponse.getResponseText().getBytes());
            out.flush();
        }

        return null;
    }

如您所见,将javascript发送到服务器,然后由DispatcherServlet将其分派给控制器。控制器然后invokes正确的方法调用并通过response.getOutputStream().write(....)返回响应。

控制器然后必须返回null,以便DispatcherServlet不做任何回报。

就我而言,AjaxResponse是一个界面,响应可以是XmlAjaxResponseJsonAjaxResponse

java客户端然后处理从服务器返回的响应(在本例中为控制器)。

您需要在方面添加回复。希望这会有所帮助。