1.在jsp页面中嵌套 java代码:
首先jsp页面中导入java的工具类
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
//在js中插入java代码操作 <% //取出java后台设置好的userList List<Map<String,String>> userList = (List<Map<String,String>>)request.getAttribute("userList"); //如果userList的值为空则实例化 if(userList==null){ userList = new ArrayList<Map<String,String>>(); } %> //如果userList内有数据 if (<%=userList.size()%>>0) { <% //遍历list中的内容 for (Map<String,String> user : userList) { String userId = user.get("userId"); String userName = user.get("userName"); %> //在java遍历中调用js方法,传参 toAdd("<%=userId%>","<%=userName%>"); <% } %> //如果userList中无知就要把java后台设置好的两个参数拿出来做参数 }else{ //销售人员ID var userId = "${userId}"; //销售人员姓名 var userName = "${userName}"; toAdd(userId,userName); }
2.在jsp页面中forEach获取:
<c:forEach items="${messages }" var="message"> <div> <div> <p><font color="red">${message.content }</font></p> </div> <div><button onclick="LookReply(${message.mid })">查看回复</button></div> <div id="reply_${message.mid }"></div> </div> <br> </c:forEach>
3.在后台先把list转成json格式,然后js中使用var arr = eval(‘${list}');将list转成js数组。
后台
JSONArray object=JSONArray.fromObject(yourlist);
request.setAttribute("agentsList", object);
前台
var agentsList = eval('${agentsList}') for (var i = 0; i < agentsList.length; i++) { var array_element = agentsList[i]; }
4.后台还是把list转成json,js中使用var arr = jQuery.parseJSON('${list}')将list转成数组
var arr = jQuery.parseJSON('${list}') for (var i = 0; i < list.length; i++) { var array_element = list[i]; //alert(array_element.agentPhone); }
5.后台是springMVC,将查询的集合replies放进map,返回到前台。
后台:
@RequestMapping(value="/findReply") @ResponseBody public Map<String, Object> findReply(int mid){ System.out.println("mid:"+mid); List<Reply> replies=replyService.findReply(mid); Map<String, Object> map = new HashMap<String, Object>(); map.put("replies", replies); return map; }
前台:
var mid; function LookReply(mid){ $.ajax({ dataType:"json", type:"POST", url:"../reply/findReply.action", data:{mid:mid}, success:function(data){ var arr=data.replies;//如果前方代码取值不称就用这个:jQuery.parseJSON(data).replies; for(var i=0;i<data.replies.length;i++){ var name=arr[i].replier; var content=arr[i].reply; var time=arr[i].time; $('#reply_'+mid).prepend("<dl style='background-color:pink;'><dt>"+content+"</dt><dd>回复者:"+name+"</dd><dd>回复时间:"+time+"</dd></dl>"); } },error:function(data){ alert(系统错误); } }); }