最近在跟着别人做项目,刚好碰到要使用ajax,我以前从没用过ajax,就现学现用,用的是jquery中的ajax。那个项目是用ssh2搭建的,要解决的问题就是用ajax请求action,ajax要传递参数,最后要拿到action返回的数据。自己是个菜鸟,不会使用json什么的,就只能在后台action中把要在前台显示的页面代码全部组装好再传出去。关键源码如下:
(1)testAjax.jsp
<head>
<script src="${ctx}/js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function test(id){
$("#actionContent").load("index_expertList.action",{expertTypeId:id},function(responseText){
document.getElementById("display").innerHTML = responseText;
});
}
</script>
</head>
<body>
<input type="button" value="TestAjax" οnclick="test(3)"/>
<div id="actionContent"></div>
<div id="display"></div>
</body>
(2)IndexAction.java
public class IndexAction extends BaseActionSupport {
public String expertList() throws IOException{
Integer expertTypeId = Integer.parseInt(this.request.getParameter("expertTypeId"));
String expertTypeName = adminService.findExpertType(expertTypeId).getTypeName();
List<Expert> expertList = adminService.findExpertByExpertType(expertTypeId);
StringBuffer stringBuffer = new StringBuffer(); // 使用StringBuffer组装html代码
stringBuffer.append("<p class='crumbs'><span>专家</span> >> <span>" + expertTypeName + "</span> >> <span>所有专家</span></p>");
stringBuffer.append("<ul class='clearfix'>");
for(int i=0; i<expertList.size();i++){
stringBuffer.append("<li><img src='"+expertList.get(i).getImageUrl() + "' />" + "<a href='index_expertContent.action?expertId="
+ expertList.get(i).getId() + "' target='_bank'>" + expertList.get(i).getName() + "</a></li>");
if(i==5){
break;
}
}
stringBuffer.append("</ul>");
this.response.setCharacterEncoding("utf-8"); // 把组装好的html代码回传给ajax
PrintWriter out = this.response.getWriter();
out.print(stringBuffer.toString());
return null;
}
}
(3)struts.xml
<action name="index_*" method="{1}" class="com.pinzhi.action.IndexAction">
</action>