目的,在页面上点击按钮,让后端执行命令,后端反馈json,前端解晰并提出alter框
1、在struts2中,较方便的json输出,是通过google jsonplugin,下载这个包,附件中有。
2、在struts.xml 继承josn
extends="struts-default,json-default"
可以多继承
3、新建ajax.struts.xml,专门用于异步请求
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="ajax" namespace="/ajax" extends="default"> <action name="ajax_*" class="com.my.ajax.action.AjaxJsonAction" method="{1}"> <result type="json" > <param name="root">result</param> </result> </action> </package> </struts>
4、新建AjaxJsonAction类,用于后端处理得到json
/** * @author 锅巴 * @date 2011-3-6 * @description */ public class AjaxJsonAction extends ActionSupport{ private String result; /** * */ private static final long serialVersionUID = 1L; public String ajaxRequest() throws Exception { JSONObject obj = null; try{ obj = JSONObject.fromObject(getJsonMap()); }catch(Exception e){ Map<String,String> map = new HashMap<String,String>(); map.put("result", "系统错误"); obj = JSONObject.fromObject(map); } result = obj.toString(); return SUCCESS; } public String getResult() { return result; } private Map<String,String> getJsonMap(){ Map<String,String> result = new HashMap<String, String>(); result.put("result", "处理成功"); return result; } }
5、页面中的处理,用jquery
//f_get function f_ajax(id){ $.ajax({ url: "/ajax/ajaxRequest.html", data: 'mobile='+mobile, cache: false, success: function(data){ var f=jQuery.parseJSON(data); //result是json中的键名 alert(f.result); } }); }
<a href="#" onclick="f_ajax('13088777999')">发短信</a>