<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> enter name:<input type="text" id="inputdisplay" size="25" /> <button type="button" onclick=" sendMessageToServer()">send to server:</button><br/> reply received from server:<input type="text" id="textdisplay" size=30 /> <script type="text/javascript"> var xmlHttpRequest; if(window.XMLHttpRequest){ xmlHttpRequest=new XMLHttpRequest(); }else if(window.ActiveXObject){ xmlHttpRequest=new ActiveXObject("MICROSOFT.XMLHTTP"); } function sendMessageToServer(){ xmlHttpRequest.open("POST","AjaxDemoServlet?name="+document.getElementById('inputdisplay').value,true); xmlHttpRequest.onreadystatechange=receiveMessageFromServer; xmlHttpRequest.send(); documnet.getElementById('inputdisplay').value=""; } function receiveMessageFromServer(){ /* xmlHttpRequest.readyState==4 --> the XMLHttpRequest has loaded the data transfer has commpleted */ /* xmlHttpRequest.status==200 --> ok -the request was fulfilled */ if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200) document.getElementById('textdisplay').value = xmlHttpRequest.responseXML.getElementsByTagName("responseFromServer")[0].text; } </script> </body> </html>
package com.zxl.ajax; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxDemoServlet extends HttpServlet { private static final long serialVersionUID = 1L; public AjaxDemoServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { // TODO Auto-generated method stub } protected void doPost(HttpServletRequest request,IOException { // TODO Auto-generated method stub System.out.println("server received the following message from client: "+request.getParameter("name")); response.setContentType("text/xml"); response.getWriter().println("<responseFromServer>hi "+request.getParameter("name")+"</responseFromServer>"); System.out.println("server replied with the following message to client: hi "+request.getParameter("name")); } }
原文链接:https://www.f2er.com/ajax/165493.html