以下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库包含在我的项目中了?
答案 0 :(得分:1)
ajax中的流程是:
您提供的代码中缺少第4步。
在我看来,你正在使用the prototype javascript framework,这是正确的吗? 如果您查看the documentation for ajax requests和the 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
是一个界面,响应可以是XmlAjaxResponse
或JsonAjaxResponse
。
java客户端然后处理从服务器返回的响应(在本例中为控制器)。
您需要在方面添加回复。希望这会有所帮助。