先实现一下Servlet来对请求做出响应。 PostMessage.java: public class PostMessage extends HttpServlet { private static final long serialVersionUID = 1L; public PostMessage() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = request.getParameter("message"); response.getOutputStream().print( "hello" + new String(message.getBytes("utf-8"), "iso-8859-1")); } } Ajax请求方法,使用POST方式提交请求,同时使用回调方法将响应结果以列表的形式在页面上显示。 ajax.js: function postMessage(o) { var http_request = false; if (window.XMLHttpRequest) { // Mozilla, Safari,... http_request = new XMLHttpRequest(); if (http_request.overrideMimeType) { http_request.overrideMimeType('text/xml'); } } else if (window.ActiveXObject) { // IE try { //IE7以前的版本 http_request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { //IE较老版本 http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } if (!http_request) { alert('初始化XMLHttpRequst失败'); return false; } http_request.onreadystatechange = function() { if (http_request.readyState == 4) { if (http_request.status == 200) { var out = document.getElementById("list"); var m = document.createElement("li"); var text = document.createTextNode(http_request.responseText); m.appendChild(text); out.appendChild(m); // alert(http_request.responseText); } else { alert('There was a problem with the request.'); } } }; http_request.open('POST', o.action, true); http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); http_request.send("message="+o.message.value); } 在页面中调用Ajax请求方法。 index.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=UTF-8"> <title>Insert title here</title> <mce:script type="text/javascript" src="js/ajax.js" mce_src="js/ajax.js"></mce:script> </head> <body> <ol id="list"> </ol> <form action="PostMessage" οnsubmit="return false;" id="form1"> <input type="text" id="message"> <button οnclick="postMessage(document.getElementById('form1'))">发布</button> </form> </body> </html>