Ajax 处女秀
将Ajax in Action 第9章的Server端,改成了SERVLET形式的
代码如下:
<html>
<head>
<META http-equiv=Content-Type content= "text/html;charset=UTF-8 ">
</head>
<script language= "javascript ">
var XMLHttpReq;
function createXMLHttpRequest(){
if(window.XMLHttpRequest){
XMLHttpReq = new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
XMLHttpReq = new ActiveXObject( "Msxml2.XMLHTTP ");
}catch(E){
try{
XMLHttpReq = new ActiveXObject( "Microsoft.XMLHTTP ");
}catch(E){}
}
}
}
//¡¤¡罿?¦ʿ¡¥?
function sendRequest(oElem,oTarget){
var strValue = oElem.options[oElem.selectedIndex].value;
var URL = "simpleservlet ";
var strParams = 'q= ' + strValue +
"&f= " + oTarget.form.name +
"&e= " + oTarget.name;
createXMLHttpRequest();
XMLHttpReq.onreadystatechange=processResponse;
XMLHttpReq.open( "POST ",URL,true);
//POST方式,要设置Header
var contentType= 'application/x-www-form-urlencoded ';
XMLHttpReq.setRequestHeader( 'Content-Type ', contentType);
XMLHttpReq.send(strParams);
}
//¡㻭§²?o¡¥?
function processResponse(){
if(XMLHttpReq.readyState==4){
if(XMLHttpReq.status==200){
//readXml();
read2Xml();
}else{
window.alert( "Error! "+XMLHttpReq.status);
}
}
}
function read2Xml(){
var xmlDoc = XMLHttpReq.responseXML.documentElement;
if(null == xmlDoc)
window.alert( "xmlDoc is null! ");
var xSel = xmlDoc.
getElementsByTagName( 'selectElement ')[0];
var strFName = xSel.
childNodes[0].firstChild.nodeValue;
var strEName = xSel.
childNodes[1].firstChild.nodeValue;
var objDDL = document.forms[strFName].
elements[strEName];
objDDL.options.length = 0;
var xRows = xmlDoc.
getElementsByTagName( 'entry ');
for(i=0;i <xRows.length;i++){
var theText = xRows[i].
childNodes[0].firstChild.nodeValue;
var theValue = xRows[i].
childNodes[1].firstChild.nodeValue;
var option = new Option(theText,
theValue);
objDDL.options.add(option,
objDDL.options.length);
}
}
</script>
<body>
<form name= "Form1 " ID= "Form1 ">
<select name= "ddlRegion " onchange= "sendRequest(this,document.Form1.ddlTerritory) " ID= "Select1 ">
<option value= "-1 "> Pick A Region </option>
<option value= "1 "> Eastern </option>
<option value= "2 "> Western </option>
<option value= "3 "> Northern </option>
<option value= "4 "> Southern </option>
</select>
<select name= "ddlTerritory " ID= "Select2 "> </select>
</form>
</body>
</html>
Server端:
package demo;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class SimpleServlet
extends HttpServlet {
ResultSet rs = null;
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType( "text/xml ");
String strQuery = request.getParameter( "q ");
System.out.println( "q is: "+strQuery);
String strForm = request.getParameter( "f ");
String strElem = request.getParameter( "e ");
String strSql = "select Name,TerritoryID from city where Region = " +
" ' "+strQuery+ " ' ";
rs = getResultSet(strSql);
StringBuffer builder = new StringBuffer();
//构造XML文件
builder.append( " <?xml version=\ "1.0\ " encoding=\ "UTF-8\ " ?> ");
builder.append( " <selectChoice> ");
builder.append( " <selectElement> ");
builder.append( " <formName> " + strForm + " </formName> ");
builder.append( " <formElem> " + strElem + " </formElem> ");
builder.append( " </selectElement> ");
//将结果集以XML文档的形式表现出来
try {
rs.last();
int total = rs.getRow();
if (total > 0) {
builder.append( " <entry> ");
builder.append( " <optionText> " + "Seclect A Territory " + " </optionText> ");
builder.append( " <optionValue> -1 ");
builder.append( " </optionValue> ");
builder.append( " </entry> ");
}else{
System.out.println( "total is 0! ");
}
rs.absolute(1);
for (int i = 0; i < total; i++) {
builder.append( " <entry> ");
builder.append( " <optionText> " + rs.getString( "Name ") + " </optionText> ");
builder.append( " <optionValue> " + rs.getString( "TerritoryID ") +
" </optionValue> ");
builder.append( " </entry> ");
rs.next();
}
}
catch (Exception e) {
System.out.println(e.toString());
}
builder.append( " </selectChoice> ");
System.out.println(builder.toString());
//将XML文档写回到客户端
PrintWriter out = response.getWriter();
out.println(builder.toString());
}
//Clean up resources
public void destroy() {
}
//数据库处理函数
private ResultSet getResultSet(String sql) {
String DB_Driver = "org.gjt.mm.mysql.Driver ";
String url = "jdbc:mysql://192.168.0.10/test ";
String name = "root ";
String password = "root ";
String DB_Name = "test ";
Connection con = null;
Statement smt = null;
ResultSet temprs = null;
try {
Class.forName(DB_Driver).newInstance();
con = java.sql.DriverManager.getConnection(url, name, password);
smt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
temprs = smt.executeQuery(sql);
}
catch (Exception e) {
System.out.println(e.toString());
}
return temprs;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request,response);
}
}
对象的web.xml文件
<?xml version= "1.0 " encoding= "ISO-8859-1 "?>
<!--
Copyright 2004 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License ");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS " BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "
version= "2.4 ">
<display-name> Welcome to Tomcat </display-name>
<description>
Welcome to Tomcat
</description>
<!-- JSPC servlet mappings start -->
<servlet>
<servlet-name> org.apache.jsp.index_jsp </servlet-name>
<servlet-class> org.apache.jsp.index_jsp </servlet-class>
</servlet>
<servlet>
<servlet-name> simpleservlet </servlet-name>
<servlet-class> demo.SimpleServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> simpleservlet </servlet-name>
<url-pattern> /simpleservlet </url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name> org.apache.jsp.index_jsp </servlet-name>
<url-pattern> /index.jsp </url-pattern>
</servlet-mapping>
</web-app>
给自己做个笔记·····
[解决办法]
学习!