一个简单的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这种的错误。
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05