Dynamic Selection with XMLHttpRequest and Java Servlet


This topic will talk about how to create a dynamic selection in web application using XMLHttpRequest and Servlet. In this demo a car model will be changed correspond to car brand.

Demo (Chrome, FireFox). http://mysecond.phuaccount.cloudbees.net/

Step 1. Create the XML data file "car.xml" under ./data directory.

car.xml:
<?xml version="1.0"?>
<CAR>
 <BRAND NAME="TOYOTA">
  <MODEL>FORTUNER</MODEL>
  <MODEL>CAMRY</MODEL>
  <MODEL>ALTIS</MODEL>
  <MODEL>VIOS</MODEL>
 </BRAND>
 <BRAND NAME="HONDA">
  <MODEL>CIVIC</MODEL>
  <MODEL>CITY</MODEL>
  <MODEL>JAZZ</MODEL>
 </BRAND>
</CAR>


Step 2. Create a java class to retrieve data.

Car.java:
package com.java.dynamic.demo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * @author [email protected]
 * require library: crimson.jar
 */
public class Car {

  public static void main(String[] args) {
    try {
      Car car = new Car();
      car.getCar();
      //car.getBrand();
      //car.getModel("HONDA");
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    }
  }
 
  private DocumentBuilderFactory factory;
  private Document doc;
 
  public Car() throws SAXException, IOException, ParserConfigurationException {
    factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
   
    // Create the builder and parse the file
    doc = factory.newDocumentBuilder().parse(new File("./data/car.xml"));     
  }
 
  public Car(HttpServletRequest request) throws SAXException, IOException, ParserConfigurationException {
    factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
   
    String pathInfo = request.getRequestURL().toString();
    pathInfo = pathInfo.substring(0, pathInfo.lastIndexOf(':'));
    int port = request.getServerPort();
    pathInfo += ":"+String.valueOf(port);
    pathInfo += request.getContextPath();
    pathInfo += "/data/car.xml";
    //System.out.println("path: " + pathInfo);
   
    URL url = new URL(pathInfo);
    InputStream inputXML = url.openStream();
   
    // Create the builder and parse the file
    doc = factory.newDocumentBuilder().parse(inputXML);
  }
 
  public String getCar() {
    String result = null;
    NodeList nodes = doc.getElementsByTagName("CAR");
    //System.out.println("There are " + nodes.getLength() +  " elements.");
    for (int i=0; i<nodes.getLength(); i++) {
      if (nodes.item(i).hasChildNodes()) {
        result = nodes.item(i).getChildNodes().toString();
        //System.out.println("Result: " + result);
      }
    }
    return result;
  }
 
  public String getBrand() {
    String result = null;
    String data;
      NodeList nodes = doc.getElementsByTagName("BRAND");
      //System.out.println("There are " + nodes.getLength() +  " elements.");
      for (int i=0; i<nodes.getLength(); i++) {
        if (nodes.item(i).hasAttributes()) {
          data = nodes.item(i).getAttributes().item(0).getNodeValue();
          //System.out.println("NodeValue: " +data);
          result = data;
        }
      }
    return result;
  }
 
  public String getModel(String brand) {
    String result = null;
    NodeList nodes = doc.getElementsByTagName("BRAND");
    String attrValue;
    NodeList childNodes;
    for (int i=0; i<nodes.getLength(); i++) {
      if (nodes.item(i).hasAttributes()) {
        attrValue = nodes.item(i).getAttributes().item(0).getNodeValue();
        if (attrValue.equals(brand))
        if (nodes.item(i).hasChildNodes()) {
          childNodes = nodes.item(i).getChildNodes();
          //System.out.println("ChildNode: " + childNodes);
          result = childNodes.toString();
          //System.out.println("Data: " + result);
          //ProcessChildNodes(childNodes);
          i = nodes.getLength();
        }
      }
    }
    return result;
  }
 
  public void ProcessChildNodes(NodeList node) {
    for (int j=0; j<node.getLength(); j++) {
      System.out.println("Type: " + node.item(j).getNodeType());
      if (node.item(j).getNodeType() == 1)
      if ("MODEL".equals(node.item(j).getNodeName())) {
        System.out.println("Name: " + node.item(j).getNodeName());
        System.out.println("Value: " + node.item(j).getFirstChild());
      }
    }   
  }
 
}


Step 3. Create a Servlet class for AJAX call to get car brand.

CarServlet.java:
package com.java.dynamic.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

/**
 * Return car data and stream out to client. 
 * @author [email protected] 
 */
public class CarServlet extends HttpServlet {
   
  private static final long serialVersionUID = 1L;
  private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";
   
  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
    response.setContentType(CONTENT_TYPE);
    try {
      Car car = new Car(request);
      String carString = car.getCar();
      PrintWriter out = response.getWriter();
      out.println(carString);
      out.flush();
      out.close();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    }
  }
 
  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
    doGet(request, response);
  }
}


Step 4. Create a Servlet class for AJAX call to get car model.

ModelServlet.java:
package com.java.dynamic.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

/**
 * Return car model for a given brand and stream out to client. 
 * @author [email protected] 
 */
public class ModelServlet extends HttpServlet {
   
  private static final long serialVersionUID = 1L;
  private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";
   
  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    String brand = request.getParameter("brand");
    try {
      Car car = new Car(request);
      String carString = car.getModel(brand);
      PrintWriter out = response.getWriter();
      out.println(carString);
      out.flush();
      out.close();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    }
  }
 
  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    doGet(request, response);
  }
}


Step 5. Create a Sale class to provide sale history.

Sale.java:
package com.java.dynamic.demo;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Generate sale history report. 
 * @author [email protected] 
 */
public class Sale {

  /**
   * For testing
   */
  public static void main(String[] args) {
    Sale sale = new Sale();
    System.out.println(""+sale.getSaleReport());
  }
 
  private String brand = null;
  private String model = null;
  private String[] region = {"North", "South", "East", "West"};
  private String[] monthName = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  private SimpleDateFormat sdf = new SimpleDateFormat("yyyy,MM");
 
  /**
   * Constructor for testing
   */
  public Sale() {
  }
 
  /**
   * Constructor for application
   * @param brand, brand of a car
   * @param model, model of a car of that brand
   */
  public Sale(String brand, String model) {
    this.brand = brand;
    this.model = model;
  }
 
  /**
   * Get a report 12 months back
   * @return result as XML string
   */
  public String getSaleReport() {
    StringBuffer sb = new StringBuffer();
    String date = sdf.format(new Date());
    String[] dates = date.split(",");
    int month = new Integer(dates[1]).intValue();
    String year = dates[0];
    sb.append("<RESULT>");
    sb.append("<CAR BRAND=\""+brand+"\" MODEL=\""+model+"\">");
    for (int i=0; i<region.length; i++) {
      sb.append("<REGION REGION=\""+region[i]+"\">");
      for (int j=month-1; j<12; j++) {
        sb.append("<SALE MONTH=\""+monthName[j]+"\" YEAR=\""+(new Integer(year).intValue()-1)+"\">");
        sb.append(String.valueOf(Math.floor(Math.random()*100)));
        sb.append("</SALE>");
      }
      if (month > 0) {
        for (int j=0; j<month-1; j++) {
          sb.append("<SALE MONTH=\""+monthName[j]+"\" YEAR=\""+year+"\">");
          sb.append(String.valueOf(Math.floor(Math.random()*100)));
          sb.append("</SALE>");
        }
      }
      sb.append("</REGION>");
    }
    sb.append("</CAR>");
    sb.append("</RESULT>");
    return sb.toString();
  }
}


Step 6. Create a Servlet class to get sale report.

SaleServlet.java:
package com.java.dynamic.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Return sale history for a given brand and model, then stream out to client. 
 * @author [email protected] 
 */
public class SaleServlet extends HttpServlet {
   
  private static final long serialVersionUID = 1L;
  private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";
   
  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    String brand = request.getParameter("brand");
    String model = request.getParameter("model");
    Sale sale = new Sale(brand, model);
    PrintWriter out = response.getWriter();
    out.println(sale.getSaleReport());
    out.flush();
    out.close();
  }
 
  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    doGet(request, response);
  }
}


Step 7. Create web.xml

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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">
     
  <servlet>
    <servlet-name>CarServlet</servlet-name>
    <servlet-class>com.java.dynamic.demo.CarServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>ModelServlet</servlet-name>
    <servlet-class>com.java.dynamic.demo.ModelServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>SaleServlet</servlet-name>
    <servlet-class>com.java.dynamic.demo.SaleServlet</servlet-class>
  </servlet>
   
  <servlet-mapping>
    <servlet-name>SaleServlet</servlet-name>
    <url-pattern>/sale</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ModelServlet</servlet-name>
    <url-pattern>/model</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>CarServlet</servlet-name>
    <url-pattern>/car</url-pattern>
  </servlet-mapping>
   
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

</web-app>


Step 8. Create html page.

index.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE> Dynamic Selection </TITLE>
  <META NAME="Generator" CONTENT="Custom edit">
  <META NAME="Author" CONTENT="[email protected]">
  <META NAME="Keywords" CONTENT="Some keyword">
  <META NAME="Description" CONTENT="">
  <link REL="stylesheet" TYPE="text/css" HREF="./styles/mypage.css">
</HEAD>

<script language='javascript'>

var timeStart = null;

function wait(w)
{
  var ph = document.getElementById("phWait");
  ph.style.display = (w) ? "block" : "none";
  if (w) {
    timeStart = new Date();
  }
  else {
    var showTime = document.getElementById("respTime");
    showTime.innerHTML = "Response time : "+(new Date() - timeStart) + " ms";
  }
}

// Replace string
function replaceAll( str, replacements ) {
  for ( i = 0; i < replacements.length; i++ ) {
    var idx = str.indexOf( replacements[i][0] );   
    while ( idx > -1 ) {
      str = str.replace( replacements[i][0], replacements[i][1] );
      idx = str.indexOf( replacements[i][0] );
    } 
  } 
  return str;
}

// Clear selection box
function clearSelectionBox(id, msg) {
  var selBox = document.getElementById(id);
  // clear data in the list
  while(selBox.options.length > 0)
     selBox.remove(0);
  // add display element
  var o = document.createElement("OPTION");
  selBox.options.add(o);
  o.value = "";
  o.innerHTML = msg;
  // disable dropdown
  selBox.disabled = true;
}
   
var XMLHttpFactories = [
  function () {return new XMLHttpRequest()},
  function () {return new ActiveXObject("Msxml2.XMLHTTP")},
  function () {return new ActiveXObject("Msxml3.XMLHTTP")},
  function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

function createXMLHTTPObject() {
  var xmlhttp = false;
  for (var i=0;i<XMLHttpFactories.length;i++) {
    try {
      xmlhttp = XMLHttpFactories[i]();
    }
    catch (e) {
      continue;
    }
    break;
  }
  return xmlhttp;
}

function sendRequest(url, callback, postData) {
  var req = createXMLHTTPObject();
  if (!req) return;
  var method = (postData) ? "POST" : "GET";
  req.open(method,url,true);
  req.setRequestHeader('User-Agent','XMLHTTP/1.0');
  if (postData)
    req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
  req.onreadystatechange = function () {
    if (req.readyState != 4) return;
    if (req.status != 200 && req.status != 304) {
      alert('HTTP error ' + req.status);
      return;
    }
    callback(req);
  }
  if (req.readyState == 4) return;
  req.send(postData);
}

var xmlhttp;
function GetCarBrand()
{
  wait(true);
  var url = "http://localhost:8800/dynamic/car";
  xmlhttp = null;
  xmlhttp = createXMLHTTPObject();
 
  if (xmlhttp != null) {
    xmlhttp.onreadystatechange = onResponseBrand;
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
  }
  else {
    alert("Your browser does not support XMLHTTP.");
  }
}

function onResponseBrand()
{
  if(xmlhttp.readyState!=4) return;
  if(xmlhttp.status!=200) {
    alert("Problem retrieving car XML data");
    return;
  }
   
  //alert(xmlhttp.responseText); 
 
  brand_id = "brand";
  x = xmlhttp.responseXML.documentElement.getElementsByTagName("BRAND");
  //alert(x[0].attributes.getNamedItem("NAME").value);
  if (x.length > 0) {
    var selBox = document.getElementById(brand_id);
    // clear data in the list
    while(selBox.options.length > 0)
       selBox.remove(0);
    for (i=0; i<x.length; i++)
    {
      // fill the list
      var o = document.createElement("OPTION");
      selBox.options.add(o);
      o.value = x[i].attributes.getNamedItem("NAME").value;
      o.innerHTML = x[i].attributes.getNamedItem("NAME").value;
      // enable dropdown
      selBox.disabled = false;
    }
    GetCarModel();
  }
  else {
   clearSelectionBox(brand_id, "No data..");
  }
  wait(false);
}

function GetCarModel()
{
  wait(true);
  var carBrand = document.getElementById("brand");
  var url = "http://localhost:8800/dynamic/model?brand="+carBrand.value;
 
  xmlhttp = null;
  xmlhttp = createXMLHTTPObject();
 
  if (xmlhttp != null) {
    xmlhttp.onreadystatechange = onResponseModel;
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
  }
  else {
    alert("Your browser does not support XMLHTTP.");
  }
}

function onResponseModel()
{
  if(xmlhttp.readyState!=4) return;
  if(xmlhttp.status!=200) {
    alert("Problem retrieving car model XML data");
    return;
  }
   
  //alert(xmlhttp.responseText); 
 
  box_id = "model";
  x = xmlhttp.responseXML.documentElement.getElementsByTagName("MODEL");
 
  if (x.length > 0) {
    var selBox = document.getElementById(box_id);
    // clear data in the list
    while(selBox.options.length > 0)
       selBox.remove(0);
    for (i=0; i<x.length; i++)
    {
      // fill the list
      var o = document.createElement("OPTION");
      selBox.options.add(o);
      o.value = x[i].firstChild.nodeValue;
      o.innerHTML = x[i].firstChild.nodeValue;
      // enable dropdown
      selBox.disabled = false;
    }
  }
  else {
   clearSelectionBox(box_id, "No data..");
  }
  wait(false);
}

function GetSaleReport()
{
  wait(true);
  var url = "http://localhost:8800/dynamic/sale";
  var carBrand = document.getElementById("brand");
  url += "?brand="+carBrand.value;
  var carModel = document.getElementById("model");
  url += "&model="+carModel.value;
  //alert(url);
 
  xmlhttp = null;
  xmlhttp = createXMLHTTPObject();
 
  if (xmlhttp != null) {
    xmlhttp.onreadystatechange = onResponseSale;
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
  }
  else {
    alert("Your browser does not support XMLHTTP.");
  }
}

// Parse data and store in report grid
function onResponseSale() {

  if(xmlhttp.readyState!=4) return;
  if(xmlhttp.status!=200) {
    alert("Problem retrieving sale report XML data");
    return;
  }
 
  var result = "<table bgcolor=#CCCCCC cellpadding=0 cellspacing=0 border=0>";
  result += "<tr><td>";
  result += "<!-- Title -->";
  result += "<table bgcolor=#6699CC cellpadding=0 cellspacing=0 border=0 width=100%>";
  result += "<tr bgcolor=#6699CC>";
  result += "<td width=100%><div align=left>";
  result += "<font color=#ffffff>";
 
  //alert(xmlhttp.responseText); 
 
  x = xmlhttp.responseXML.documentElement.getElementsByTagName("CAR");
  var brand = x[0].attributes.getNamedItem("BRAND").value;
  var model = x[0].attributes.getNamedItem("MODEL").value;
  //alert(brand+", "+model);
 
  result += "<b>&nbsp;Brand:&nbsp;"+brand+",&nbsp;Model:&nbsp;"+model+"</b>";
  result += "</font></div></td></tr>";
  result += "<tr bgcolor=#eeeeee><td>";
  result += "<table bgcolor=#cccccc cellpadding=0 cellspacing=0 border=0 width=100%>";
  result += "<tr><td>";
  result += "<table bgcolor=#cccccc cellpadding=0 cellspacing=1 border=0 width=100%>";
 
  x = xmlhttp.responseXML.documentElement.getElementsByTagName("REGION");

  result += "<!-- Title -->";
  result += "<tr bgcolor=#336699>";
  result += "<td nowrap>";
  result += "<font color=#ffffff>";
  result += "<b>&nbsp;Region&nbsp;</b>";
  result += "</font></td>";
 
  xx = x[0].childNodes;
   
  if (xx.length > 0) {
    for (i=0; i<xx.length; i++)
    {
      if ( xx[i].nodeName == "SALE" ) {    
        result += "<td nowrap>";
        result += "<font color=#ffffff>";
        result += "<b>&nbsp;"+xx[i].attributes.getNamedItem("MONTH").value+"&nbsp;</b>";
        result += "</font></td>";
      }
    }
  }
  result += "</tr>";
 
  result += "<!-- Data -->";
  if (x.length > 0) {
    for (j=0; j<x.length; j++)
    {
      result += "<tr bgcolor=#ffffff>";
      result += "<td nowrap>";
      result += "&nbsp;"+x[j].attributes.getNamedItem("REGION").value+"&nbsp;";
      result += "</td>";
     
      xx = x[j].childNodes;
       
      if (xx.length > 0) {
        for (i=0; i<xx.length; i++)
        {
          if ( xx[i].nodeName == "SALE" ) {    
            result += "<td align=right nowrap>";
            result += "&nbsp;"+xx[i].firstChild.nodeValue+"&nbsp;";
            result += "</td>";
          }
        }
      }
      result += "</tr>";
    }
  }
  result += "</table>";
  result += "</td></tr></table>";
  result += "</td></tr></table>";
  result += "</td></tr></table>";
  result += "<img src='./images/java_xml.jpg'>";
 
  var o = document.getElementById("result");
  o.innerHTML = result;
 
  wait(false);
  timeStart = null;
}
          
</script>

</HEAD>

<BODY marginwidth="0" marginheight="0" leftmargin="0" topmargin="0" onload="GetCarBrand()">

<!-- Header section -->   
<table border="0" width="100%" cellspacing="0" cellpadding="0" bgcolor="#336699">
<tr><!-- Logo + Title -->
<td rowspan="2" width="48" class="mainheader"><a href=""><img src="./images/java_icon.gif" alt="" width="48" height="48" border="0"></a></td>
<td rowspan="2" class="headerTitle">Dynamic Selection Demo</td>
</tr><!-- Logo + Title -->
</table>

<!-- Menu Bar section -->
<table cellSpacing=0 cellPadding=0 width="100%" border=0 bgcolor="#003366">
<tr>
  <td class="headerLink" height="15" valign="middle">
    <font color="#FFFFFF" size="1px">
      &nbsp;>&nbsp;<A href="sample.html" class="headerLink">Home</A>
      > Example > Some Information
    </font>
  </td>
  <td align=Right class="headerLink" >
    <font color="#FFFFFF" size="1px">
    Welcome to Dynamic Selection&nbsp;
    </font>
  </td>
</tr>
</table>

<!-- Body section -->
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<!-- first column -->
<td width="208" valign="top">

<!-- begin input data -->
<table bgcolor="#6699CC" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
  <td>
    <table bgcolor="#6699CC" cellpadding="3" cellspacing="1" border="0" width="100%">
    <tr bgcolor="#6699CC">
      <td width="100%">
        <div align="center"><font color="#ffffff">
        <b>&nbsp;Selection&nbsp;</b>
        </font></div>
      </td>
    </tr>

    <tr bgcolor="#ffffff">
      <form id="frmDemo" name="frmDemo" action="" method="post">
      <td>
       <label>Brand:</br>
      <select name="brand" id="brand" onchange="GetCarModel();">
      </select>
      <br>
       <label>Model:</br>
      <select name="model" id="model"></select>
      <br><br>
      <img src="./images/btn_submit.gif" onclick="GetSaleReport()" border="0">
      <!--input type="image" id="" src="./images/btn_submit.gif" onclick="GetSaleReport()" border="0"/ -->
       <div id="phWait" style="display:none; margin: 0px 0px 0px 0px; padding: 1px; border: 3px solid #ffa300; width: 199px; text-align: center;">Please wait... <img src="./images/loading.gif" width="123" height="6" /></div>
       <div id="respTime"></div>
     </td>
     </form>
    </tr>
    </table>
  </td>
</tr>
</table>
<!-- end input data -->

<!-- second column -->
<td width="10" nowrap>
</td>

<!-- third column -->
<td valign="top">
<!-- display data -->

<div id="result">
<table bgcolor="#6699CC" cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
  <td>
    <table bgcolor="#6699CC" cellpadding="3" cellspacing="1" border="0" width="100%">
    <tr bgcolor="#6699CC">
      <td width="100%">
        <div align="center"><font color="#ffffff">
        <b>&nbsp;About&nbsp;</b>
        </font></div>
      </td>
    </tr>

    <tr bgcolor="#ffffff">
      <td>
      <p>This demonstration shows how to create a dynamic selection by using AJAX and Servlet.
      You will see a car model is changed correspond to a car brand.</p>
      <img src="./images/java_xml.jpg">
      </td>
    </tr>
    </table>
  </td>
</tr>
</table>
</div>

<!-- end display data -->
</td>
</table>

<br>

<!-- Footer section -->
<table border="0" width="100%" cellpadding="0" cellspacing="0" bgcolor="#003366">
<tr>
  <td class="footer" width="94%" valign="top" height="15">
    <table width="100%" border="0" cellpadding="0" cellspacing="0" height="15">
    <tr>
      <td class="footer">
      &nbsp;<a Class=footerlink href="index.html"><span class="footer">Home</span></a>
      </td>
    </tr>
    </table>
  </td>
  <td class="footer" width="12%" align="right" height="15">
     <span class="footer">Footer Bar</span>
  </td>
</tr>
</table>

<!-- Copyright section -->
<table cellSpacing=0 cellPadding=0 width="100%" border=0>
<tr>
  <td align=Left class="copyright" >
    <font color=gray size="1px">Developed by&nbsp;: [email protected]&nbsp;
    </font>
  </td>
  <td align=Right class="copyright" >
    <font color=gray size="1px">August 2008&nbsp;
    </font>
  </td>
</tr>

</BODY>
</HTML>


Lastly build together a war file and deploy in application server.
Tested with JBoss-4.0.5GA, IE-6.0, FireFox-3.0.

Last update 26-Mar-2009: Modify "index.html" to support browser FireFox-3.0.
What changed: 
1. Change from onload="GetCarBrand(),GetCarModel()" to onload="GetCarBrand()".
2. Move GetCarModel() to under GetCarBrand().

You can download source code and example war file: http://www.mediafire.com/file/gyofuday3jk/dynamic_selection_ie_firefox.zip

คำสำคัญ (Tags): #ajax#xmlhttprequest
หมายเลขบันทึก: 203828เขียนเมื่อ 27 สิงหาคม 2008 14:20 น. ()แก้ไขเมื่อ 18 ธันวาคม 2013 16:16 น. ()สัญญาอนุญาต: ไม่สงวนสิทธิ์ใดๆจำนวนที่อ่านจำนวนที่อ่าน:


ความเห็น (0)

ไม่มีความเห็น

พบปัญหาการใช้งานกรุณาแจ้ง LINE ID @gotoknow
ClassStart
ระบบจัดการการเรียนการสอนผ่านอินเทอร์เน็ต
ทั้งเว็บทั้งแอปใช้งานฟรี
ClassStart Books
โครงการหนังสือจากคลาสสตาร์ท