Basic AJAX XMLHttpRequest Support IE and FireFox


Here below is a basic AJAX call with XMLHttpRequest and Java Servlet. Tested with IE6.0 and FireFox3.0. I try to use the MVC (Model-View-Controller) for this demo.
1. Create a model class. This model class represents your business logic. In the real work you may use this class to connect and query data from database.
HelloWorld.java:

package mvc.demo;

public class HelloWorld {
 public String sayHello() {
  return "Hello World!";
 }
 
 public String sayHello(String userName) {
  return "Hello "+userName;
 }
}

2. Create a controller class.
HelloWorld.java:

package mvc.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;

public class HelloResponse extends HttpServlet {

  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 {

    String user = request.getParameter("name1");
    String hello;
  
    HelloWorld helloWorld = new HelloWorld();
    if ((user == null) || (user.equals("")))
      hello = helloWorld.sayHello();
    else
      hello = helloWorld.sayHello(user);

    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    request.setAttribute("result", hello);
    out.println(hello);
    out.close();
  
  }
  
}

3. Create the web deployment descriptor.
web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
  <display-name>Basic AJAX</display-name>
 
  <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>mvc.demo.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/sayHello</url-pattern>
  </servlet-mapping>
 
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

  <welcome-file-list>
   <welcome-file>
      index.html
    </welcome-file>
  </welcome-file-list>
</web-app>

4. Create a view (HTML page).
index.html:

<script>

var xmlhttp=null;
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 GetMessage()
{
  var url = "/helloWorld/sayHello"; // This is a Java servlet, can be any web url like php/asp/jsp
  xmlhttp = null;
  xmlhttp = createXMLHTTPObject();
  
  if (xmlhttp != null) {
    xmlhttp.onreadystatechange = onResponseMessage;
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null);
  }
  else {
    alert("Your browser does not support XMLHTTP.");
  }
}

function onResponseMessage()
{
  if(xmlhttp.readyState!=4) return;
  if(xmlhttp.status!=200) {
    alert("Problem retrieving car XML data");
    return;
  }
    
  document.getElementById("show_txt").innerHTML=xmlhttp.responseText;
  
}

</script>

<body onload="GetMessage()">

<table bgcolor="#6699CC" cellpadding="0" cellspacing="0" border="0">
<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;Information&nbsp;</b>
            </font></div>
        </td>
    </tr>

    <tr bgcolor="#eeeeee">
      <td>
    <div id="show_txt"></div>
      </td>
    </tr>
</table>
</td></tr></table>

</body>


Note: sayHello is a Java servlet that return the message "Hello World". It could be any web url like php/asp/jsp that return the message.
คำสำคัญ (Tags): #ajax#javascript#xmlhttprequest
หมายเลขบันทึก: 251207เขียนเมื่อ 27 มีนาคม 2009 10:33 น. ()แก้ไขเมื่อ 11 ธันวาคม 2012 13:46 น. ()สัญญาอนุญาต: ไม่สงวนสิทธิ์ใดๆจำนวนที่อ่านจำนวนที่อ่าน:


ความเห็น (0)

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

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