struts2实现Ajax实例

来源:互联网 发布:php int加括号 编辑:程序博客网 时间:2024/05/19 13:18

1.jsp页面jQuery

<span style="font-size:18px;"><script type="text/javascript" language="javascript"> $(function(){$("#typeSelect").bind("change",function(){//alert($("#typeSelect").val());//$("#textCondition").val("");var url="ajaxAction.do";var type=$("#typeSelect").val();//alert(type);if(type=="type"){//alert(type);$("#textCondition").remove(); var select = $("<select id='textCondition' name='condition' class='select' />").insertAfter($("#typeSelect")); var level = $("#level").val(); var ps={"level":level};$.post(url,ps,function(dataMap){//有数据var html="";$.each(dataMap.data,function(i,d){if(d.dr == 1){html+='<option value="'+(d.level)+'">'+(d.title)+'</option>';}});select.html(html);});             select.css("height","36px");            select.css("width","230px");}else{$("#textCondition").remove();$("<input type='text' id='textCondition' name='condition' class='textbox textbox_225' placeholder='输入关键字进行查询'/>").insertAfter($("#typeSelect"));}});</span>
2.action类

<span style="font-size:18px;">public class AjaxAction extends BaseAction {private ICenterService centerService = (ICenterService) ServiceProvinder.getService(ICenterService.SERVICE_NAME);//获得返回的json数据,这个必须要getter方法private Map<String, Object> dataMap;public Map<String, Object> getDataMap() {return dataMap;}//提交Action的方法public String centerMenu() {//获得一级栏目String level=request.getParameter("level"); //根据一级栏目查询二级栏目内容 List<Center> centers=centerService.findConditionByType(level); //实例化map对象 dataMap =new HashMap<String, Object>(); //将查询的集合添加到map里 dataMap.put("data", centers); //返回一个string参数,用于找struts.xml中的resultreturn "jsonData";}}</span>

3.Center是一个实体类

4.struts.xml配置

<!-- 配置Ajax返回json数据,先导入struts2-json-plugin-2.3.16.3.jar包 ,然后新建package ,要继承json-default --><package name="ajax" extends="json-default" ><!-- 配置action --><action name="ajaxAction" class="cn.edu.xmu.cceer.web.action.AjaxAction" method="centerMenu">        <!-- 将返回类型设置为json type必须为json -->        <result name="jsonData" type="json">         <param name="root">dataMap</param>        </result>       </action></package>



5.用到的jar包


0 0
原创粉丝点击