您的位置:首页 > 其它

ajax 二级联动示例

2009-03-21 01:34 78 查看
最近研究一下ajax和<html>互动 ^_^ 感觉还真是不错

首先创建两个实体类 get set方法

国家

public class Country implements Serializable{

private static final Long serialVersionUID=123456789098765432L;

private Long id;

private String name;


private Set<City> city=new HashSet<City>(0);

城市

public class City implements Serializable{

private static final long serialVersionUID=-250998437593347316L;

private Long id;

private String name;


private Country country;

一对多关系 持久层 用hibernate 这里就不多说了

两个类要和ActionForm放在同个包下

ActionForm

public class RegisterForm extends ActionForm {
/**
*
*/


private Country country=new Country();


public Collection<Country> getCountrys(){
List<Country> list=new ArrayList<Country>();
Show show=new ShowImpl();
list=show.show();

return list;
}

}


然后是action了

public class OpentionAction extends MappingDispatchAction {

public ActionForward toAjax(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
RegisterForm reForm=(RegisterForm)form;
return mapping.findForward("toAjax");
}


还有servlet

public class SelectServlet extends HttpServlet{

private static final long serialVersionUID = 1L;

public SelectServlet()
{
super();
}


public void destroy()
{
super.destroy();
}


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// response.setCharacterEncoding("GBK");
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("UTF-8");
String targetId =request.getParameter("id").toString();
System.out.println("haha"+targetId);
// 获得请求中参数为id的值
String xml_start = "<selects>";
String xml_end = "</selects>";
String xml = "";
Show show=new ShowImpl();


List<City> list1=show.show2();
Iterator it1=list1.iterator();


while(it1.hasNext()){

City city=(City)it1.next();


System.out.println("haha"+city.getCountry().getId().toString());


if(city.getCountry().getId().toString().equalsIgnoreCase(targetId)){
xml +="<select><value>"+city.getId()+"</value><text>"+city.getName()+"</text></select>";
}

}
if (targetId.endsWith("0"))
{
xml = "<select><value>0</value><text>请选择</text></select>";
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}


public void init() throws ServletException
{
}

}


下面是页面了index.jsp

中写一个<a href ="ajax.do">ajax</a>

ajax.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage=""%>
<
%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<
%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<
%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

<html>
<head>
<title>二级菜单联动演示</title>
<script type="text/javascript">
var req;
window.onload=function()
{//页面加载时的函数
}

function Change_Select(){//当第一个下拉框的选项发生改变时调用该函数
var province = document.getElementById('country.name').value;
var url = "select?id="+ escape(province);
if(window.XMLHttpRequest){
req = new XMLHttpRequest();
}else if(window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if(req){
req.open("GET",url,true);
//指定回调函数为callback
req.onreadystatechange = callback;
req.send(null);
}
}
//回调函数
function callback(){
if(req.readyState ==4){//4为返回
if(req.status ==200){//200为完成
parseMessage();//解析XML文档
}else{
alert("不能得到描述信息:" + req.statusText);
}
}
}
//解析返回xml的方法
function parseMessage(){
var xmlDoc = req.responseXML.documentElement;//获得返回的XML文档
var xSel = xmlDoc.getElementsByTagName('select');
//获得XML文档中的所有<select>标记
var select_root = document.getElementById('city');
//获得网页中的第二个下拉框
select_root.options.length=0;
//每次获得新的数据的时候先把每二个下拉框架的长度清0

for(var i=0;i<xSel.length;i++){
var xValue = xSel[i].childNodes[0].firstChild.nodeValue;
//获得每个<select>标记中的第一个标记的值,也就是<value>标记的值
var xText = xSel[i].childNodes[1].firstChild.nodeValue;
//获得每个<select>标记中的第二个标记的值,也就是<text>标记的值

var option = new Option(xText, xValue);
//根据每组value和text标记的值创建一个option对象

try{
select_root.add(option);//将option对象添加到第二个下拉框中
}catch(e){
}
}
}
</script>
</head>


<body>
<div align="center">
<html:form>
<table width="70%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center">
二级联动示例
</td>
</tr>
<tr>
<td>
<html:select property="country.name" onchange="Change_Select()">
<option value="0">
请选择
</option>
<html:optionsCollection property="countrys" label="name" value="id" />
</html:select>
<select name="city" id="city">
<!--第二个下拉菜单-->
<option value="0">
请选择
</option>
</select>
</td>
</tr>
<tr>
<td>
</td>
<tr>
</table>
</html:form>
</div>
</body>
</html>


<struts-config>

<form-beans>
<form-bean name="registerForm" type="form.RegisterForm"/>
</form-beans>

<action-mappings>

<action path="/ajax" type="action.OpentionAction"
name="registerForm" parameter="toAjax" scope="request" >
<forward name="toAjax" path="/ajax.jsp"/>
</action>
</action-mappings>

<!-- message-resources parameter="com.tarena.struts.message.MessageResources"/ -->

</struts-config>


web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>SelectServlet</servlet-name>
<servlet-class>com.SelectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ActionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SelectServlet</servlet-name>
<url-pattern>/select</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


strus-config.xml
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: