自己在网上找资料的时候,确实很纠结呢,东拼西凑的,虽然这个写的东西很简单,但是却花费我不少功夫,为了帮助后面的同学,果断贴代码,希望对大家有用!
功能描述:使用XMLHttpRequest实现异步调用,从而实现select级联下拉菜单的效果。
项目总贴截图如下(主要是给大家看看引入的jar包):
Action类的代码:
package com.action;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class AjaxTest1 extends ActionSupport {
private Map<String,List<String>> datas;
private List<String> provinces;
private List<String> citys;
public AjaxTest1(){
datas = new HashMap<String,List<String>>();
String[] c1 = new String[]{"武汉","襄樊","荆州","宜昌"};
String[] c2 = new String[]{"海淀","昌平","朝阳"};
datas.put("湖北", Arrays.asList(c1));
datas.put("北京", Arrays.asList(c2));
}
public List<String> getProvinces() {
return provinces;
}
public void setProvinces(List<String> provinces) {
this.provinces = provinces;
}
public List<String> getCitys() {
return citys;
}
public void setCitys(List<String> citys) {
this.citys = citys;
}
public String loadProvinces(){
List<String> list = new ArrayList<String>();
Set<String> set = datas.keySet();
for(String s:set){
list.add(s);
}
System.out.println(list);
this.setProvinces(list);
System.out.println("provinces:"+provinces);
return SUCCESS;
}
public String loadCitys(){
String province = ServletActionContext.getRequest().getParameter("province");
//this.setCitys(datas.get("湖北"));
System.out.println("返回的province的值是:"+province);
List<String> list = new ArrayList<String>();
this.setCitys(datas.get(province));
return SUCCESS;
}
}
struts.xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<!-- <package name="default" namespace="/" extends="struts-default">
<default-action-ref name="index" />
<global-results>
<result name="error">/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="error"/>
</global-exception-mappings>
<action name="index">
<result type="redirectAction">
<param name="actionName">HelloWorld</param>
<param name="namespace">/example</param>
</result>
</action>
</package>
<include file="example.xml"/>
Add packages here -->
<package name="test1" namespace="/" extends="json-default">
<action name="loadprovinces" class="com.action.AjaxTest1" method="loadProvinces">
<result name="success" type="json">
<!--<param name="includeProperties">provinces</param>
-->
<param name="excludeProperties">citys</param>
</result>
</action>
<action name="loadcitys" class="com.action.AjaxTest1" method="loadCitys">
<result type="json">
<param name="excludeProperties">provinces</param>
</result>
</action>
</package>
</struts>
index.jsp页面文件:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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="styles.css">
-->
<script type="text/javascript">
//获取XMLHttpRequest对象的方法
function createXMLHttpRequest(){
try{
xhr = new XMLHttpRequest();
}catch(e){
var MSXML =
['MSXML2.XMLHTTP.6.00','MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP','Microsoft.XMLHTTP'];
for(var n=0;n<MSXML.length;n++){
try{
xhr = new ActiveXObject(MSXML[n]);
break;
}catch(e){}
}
}
return xhr;
}
var xhr;
//xhr= createXMLHttpRequest();
function loadProvinces(){
xhr = createXMLHttpRequest();
xhr.open("post","loadprovinces.action",true);
//xhr.open("post","ajaxtest1.jsp",true);
xhr.setRequestHeader("Context-Type","application/x-www-form-urlencoded");
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200 || xhr.status == 304){
var provinceString = eval("("+xhr.responseText+")");
var pro = provinceString.provinces;
//alert("provinceString[0]:"+provinceString.provinces);
var s = "<option>-请选择省份-</option>";
for(var i=0;i<pro.length;i++){
s += "<option>"+pro[i]+"</option>";
}
document.getElementById("province").innerHTML = s;
//alert(xhr.responseText);
}
}
}
}
function loadCitys(){
xhr = createXMLHttpRequest();
xhr.open("post","loadcitys.action",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//alert(document.getElementById("province").value);
xhr.send("province="+document.getElementById("province").value);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200 || xhr.status == 304){
var cityString = eval("("+xhr.responseText+")");
var city = cityString.citys;
var s = "<option>-请选择城市-</option>";
for(var i=0;i<city.length;i++){
s += "<option>"+city[i]+"</option>";
}
document.getElementById("city").innerHTML = s;
}
}
}
}
window.onload = loadProvinces();
function showInfo(){
var info = "您所选择的省份是:<h3>"+document.getElementById("province").value+"</h3> 选择的城市是:<h3>"+document.getElementById("city").value+"</h3>";
//alert(info);
document.getElementById("info").innerHTML = info;
}
</script>
</head>
<body>
请选择省份:
<select id="province" οnchange="loadCitys(this.value)"></select>
请选择城市:
<select id="city" οnchange="showInfo()"></select>
<div id="info"></div>
<s:debug></s:debug>
</body>
</html>
好了,大功告成咯,仔细研磨研磨!