Struts+Jquery+json实现的ajax案例

来源:互联网 发布:淘宝评价记录能删除吗 编辑:程序博客网 时间:2024/05/19 00:35

方便新手学习的简单案例

首先准备齐全以下几个jar包

commons-beanutils-1.8.3.jar

commons-collections-3.2.jar

commons-lang-2.4.jar

ezmorph-1.0.6.jar

json-lib-2.2.3-jdk15.jar

 

1、Action方法的写法

 

public String show_detail() {Map map = new HashMap();    //用于封装各种java变量的容器,方便json统一格式化String s = "s";showLfb = layoutManager.findLfbWithJlbh(jlbh);if (showLfb.getLf().getFloor().equals("-2")) {showLfbLcxx = "品牌位于负二层";}if (showLfb.getLf().getFloor().equals("-1")) {showLfbLcxx = "品牌位于负一层";}showLfbleft = Integer.parseInt(new java.text.DecimalFormat("0").format(showLfb.getDpleft() * clintWidth))+ mainMargin- 5+ Integer.parseInt(new java.text.DecimalFormat("0").format(showLfb.getDpwidth() * clintWidth));showLfbtop = Integer.parseInt(new java.text.DecimalFormat("0").format(showLfb.getDptop() * clintHeight));map.put("pplogo", showLfb.getPplogo());map.put("ppname", showLfb.getPpname());map.put("jlbh", showLfb.getJlbh());map.put("showLfbLcxx", showLfbLcxx);map.put("showLfbleft",showLfbleft );map.put("showLfbtop", showLfbtop);map.put("s", s);JSONObject jsonObject = JSONObject.fromObject(map);  //将map封装为json对象msg = jsonObject.toString();    //这个是在action定义的私有String变量,专门用于存放json字符串的System.out.println(jsonObject);return "detail";}

2、struts.xml 配置 result

<result name="detail" type="json"><param name="root">msg</param> <!-- msg就是action里定义的那个存放json字符串的string变量  --></result>


3、jquery调用

$(".lfb").bind("click",function(){var url = "hlds!show_detail.action";var params = {jlbh:this.id,clintHeight:clintHeight,clintWidth:clintWidth};$.post(url,params,function(data){var obj = eval("("+data+")");$("#details").css({ "top": obj.showLfbtop, "left": obj.showLfbleft}).show();$("#details").html('<img id="mages" src="ppImage/'+obj.pplogo+'" style="width:90px;heigth:40px"/><br/><br/>'+obj.ppname+'<br/><s:property value="showLfbLcxx"/>');$("#details").bind("click",function(){self.location='hlds!show_lfb.action?jlbh='+obj.jlbh;});},"json");