1,處理的腳本語言代碼:
<script>
var which;
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processStateChange;
req.open("GET", url, true);
req.send();
}
}
}
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("characters").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
<form name="dynamicSelect">
TV Show: <select name="TVShowSelect" onChange="retrieveURL('example3GetCharacters.do?tvShow=' + this.value);">
<option value=""></option>
<option value="Babylon5">Babylon 5</option>
<option value="StargateSG1">Stargate SG-1</option>
<option value="StarTrekTNG">Star Trek: The Next Generation</option>
</select>
<br>
Characters: <span id="characters"></span>
</form>
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class GetCharactersAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm inForm, HttpServletRequest request, HttpServletResponse response) throws Exception {
String tvShow = (String)request.getParameter("tvShow");
if (tvShow == null) {
tvShow = "";
}
ArrayList characters = getCharacters(tvShow);
// but I wanted to keep this exampel simple.
String html = "<select name=/"CharactersSelect/">";
int i = 0;
for (Iterator it = characters.iterator(); it.hasNext();) {
String name = (String)it.next();
i++;
html += "<option value=/"" + i + "/">" + name + "</option>";
}
html += "</select>";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(html);
out.flush();
// This method returns a list of characters for a given TV show. If no TV
// show is selected, i.e., initial page view, am empty ArrayList is returned.
private ArrayList getCharacters(String tvShow) {//實際應用中應該是從數據庫中取數據
al.add("Jean Luc Picard");
al.add("William T. Riker");
al.add("Data");
al.add("Deanna Troi");
al.add("Geordi LaForge");
}
al.add("John Sheridan");
al.add("Delenn");
al.add("Londo Mollari");
al.add("Stephen Franklin");
al.add("Vir Cotto");
}
al.add("Samantha Carter");
al.add("Jack O'Neil");
al.add("Teal'c");
al.add("Daniel Jackson");
al.add("Baal");
}
} // End class
4.個人總結:
上面顯示代碼不過是起到一個拋磚引玉的作用,如果下拉框的內容多些,改用XML
進行傳輸較好,在頁面上再進行解析,再組裝成HTML代碼,進行賦值(此處指的對span)