AjaxDemo.html
<!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=ISO-8859-1">
<title>Supreeth Vijay </title>
</head>
<body>
enter name :<input type="text" id="inputdisplay" size="26"/>
<button type="button" onclick="sendMessageToServer()">SEND TO SERVER </button><br/>
Reply Received :<input type="text" id="textdisplay" size="40"/>
<script type="text/javascript">
var request;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
function sendMessageToServer()
{
request.onreadystatechange = receiveMessageFromServer;
request.open("POST","AjaxDemo?name="+document.getElementById('inputdisplay').value,true);
request.send();
document.getElementById('inputdisplay').value="";
}
function receiveMessageFromServer()
{
if(request.readyState == 4 && request.status == 200)
{
document.getElementById('textdisplay').value = request.responseXML.getElementsByTagName("responseFromServer")[0].text;
}
}
</script>
</body>
</html>
AjaxDemo.java(Servlet)
package com.ServletAjax;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AjaxDemo
*/
@WebServlet("/AjaxDemo")
public class AjaxDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AjaxDemo() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, 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 follwoing message"+request.getParameter("name"));
}
}
使用Ajax和Servlets实现代码
目前该程序在Internet Explorer中正常运行
点击按钮后的第二个文本框在其他浏览器中设置为未定义
答案 0 :(得分:0)
使用下面的行。
document.getElementById(&#39; textdisplay&#39;)。value = request.responseXML.getElementsByTagName(&#34; responseFromServer&#34;)[0] .firstChild.nodeValue;