一个简单的ajax获取json的例子

//一个简单的ajax获取json的例子

前台

<divid="ruleList"></div>向div里添加一段循环输出的数据

ajax代码

$.ajax({
            type: "POST",
            url: "ruleListAction.do?method=searchRuleList",
            //我们用text格式接收
            //dataType: "text", 
            //json格式接收数据
            dataType: "json",
            data:  "ruleId="+ruleId+"&ruleGroupId="+ruleGroupId+"&prodName="+prodName,
            success: function (jsonStr) {
                //实例2个字符串变量来拼接下拉列表
                //alert(jsonStr);
                //使用jquery解析json中的数据
                var ruleListTemp = "<table width=\"100%\"  border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
                
                 $.each(jsonStr, function (n, value) {
                	 //alert(value.ruleId);
                    ruleListTemp += ("<tr><td>" + value.ruleName);
                    ruleListTemp += ("</td></tr>"); 
                });
                 ruleListTemp += ("</table>");

                $("#ruleList").html(ruleListTemp); 
            }
		});

要注意的是data中是js方法中获取的变量来传值给后台获取,另外jsonStr要和后台传来的变量一致

后台代码

//异步查找具体规则
	public ActionForward searchRuleList(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		response.setCharacterEncoding("utf-8");
		
		
		String ruleId = request.getParameter("ruleId").trim();
		String ruleGroupId = request.getParameter("ruleGroupId").trim();
		String prodName = request.getParameter("prodName").trim();
		
		try{

			//根据prodName找出prodId
			Tporduction porductionByName = ruleListLogic.getPorductionByName(prodName);
			Trule rule = ruleListLogic.getRuleByProdIdAndRuleTypeCode(porductionByName.getProdId(), "1");
			
			List<TruleVersion> ruleVersionList = new ArrayList<TruleVersion>();
			ruleVersionList = ruleListLogic.getRuleVersionListByRuleIdAndGroupId(rule.getRuleId(), Integer.parseInt(ruleGroupId));	
			
			List<RuleListBean> ruleListTmp = new ArrayList<RuleListBean>();
			
			RuleListBean ruleTmp=new RuleListBean();
			
			for(int i=0;i<ruleVersionList.size();i++){
				ruleTmp.setRuleId(ruleVersionList.get(i).getComp_id().getRuleId());
				ruleTmp.setRuleNo(ruleVersionList.get(i).getComp_id().getRuleNo());
				ruleTmp.setRuleGroupId(ruleVersionList.get(i).getRuleGroupId());
				ruleTmp.setRuleName(ruleVersionList.get(i).getRuleItemName());
				ruleListTmp.add(ruleTmp);
			}
			
			//JSON
			JSONArray json = JSONArray.fromObject(ruleListTmp);
			String jsonStr = json.toString();
			
			response.getWriter().print(jsonStr);
			response.getWriter().flush();
			response.getWriter().close();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

需要注意的是JSONArray.fromObject放入的实体类不能是回环调用的类,如果实体类中有联合主键这种也会有问题,建议使用一个dto来转换成json,把需要的字段放入,这样就不会报java.lang.reflect.InvocationTargetException这种的错误。

相关推荐