1. 下载jquery.js文件放在webroot下js文件夹里
2. 配置struts.xml:
<package name="default" namespace="/" extends="struts-default"> <action name="ajaxRequest" class="net.nw.action.AjaxAction" method="execute"> </action>
3. 写AjaxAction.java:
package net.nw.action; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class AjaxAction extends ActionSupport{ private static final long serialVersionUID = 1L; private int id; private String result; public String execute() throws Exception{ if(id == 1){ result = "1:test1"; }else{ result = "1:a1"; } ServletActionContext.getResponse().getWriter().print(result); return null; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
4. jsp前端显示:
<head> <base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link rel="stylesheet" type="text/css" href="css/button.css" /> <script type="text/javascript" src="js/jquery.js" ></script> <script type="text/javascript"> function change(){ var id =$("#select1").val(); var url = "ajax.action"; var params = { 'id':id }; $.post(url, params, callback); } function callback(result,textStatus){ if(textStatus == 'success'){ if(result != null){ var select2 = $("#select2"); select2.empty(); var tmp = result.split(":"); select2.append("<option value = '"+tmp[0]+"'>"+tmp[1]+"</option>"); } } } </script> </head>
<body> 下拉框1:<s:select id="select1" list="#{1:'first',2:'second'}" onchange="change();" headerKey="-1" headerValue="--no select--"/> 下拉框2: <s:select id="select2" list="#{1:'--no select--'}"/> </body>