基于struts2,有2种标准方法实现ajax
共同的一点是,Action都需要将一个方法暴露出来,给前端javascript调用
javascript的代码都是一样的:
- function testAjax() {
-
- var $userNameInput = $("#ajax_username");
- var userName = $userNameInput.val();
-
- $.ajax({
- url : "originAjax.action",
- type : "GET",
- data : "ajaxField=" + userName,
- success : function(data, textStatus) {
- alert(data);
- }
- });
- }
这里originAjax.action,就是暴露出来供调用的地址
下面分别介绍服务端的两种写法
第一种是原生的写法,不需要依赖插件,也没有自行解析和拼装json串的功能
Action:
- public void originAjax() throws IOException {
- HttpServletResponse response = ServletActionContext.getResponse();
- PrintWriter writer = response.getWriter();
- writer.print("hello " + ajaxField);
- writer.flush();
- writer.close();
- }
|