前端代码
<script type="text/javascript"> var xmlhttp; function go(url) { xmlhttp=null; if (window.XMLHttpRequest) {// code for IE7, Firefox, Opera, etc. xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //////////////////////////////// if (xmlhttp!=null) { //alert("123"); xmlhttp.onreadystatechange=state_Change; xmlhttp.open("POST",url,true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("123="+"123"); } else { alert("Your browser does not support XMLHTTP."); } } function state_Change() { if (xmlhttp.readyState==4) {// 4 = "loaded" if (xmlhttp.status==200) {// 200 = "OK" var v1=xmlhttp.status; var v2=xmlhttp.statusText; var v3=xmlhttp.responseText; alert(v1+" "+v2+" "+v3); } else { alert("Problem retrieving XML data:" + xmlhttp.statusText); } } } </script> <body> This is my JSP page. <br> <input type="text" value="" name="123" /> <input type="button" value="提交" onclick="go('/Ajax.w3c/servlet/test');"/> </body>
后端代码:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("jinru fangfa "); String name = request.getParameter("123"); System.out.println(name); response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); response.setHeader("Cache-Control","no-cache"); PrintWriter out = response.getWriter(); out.println("yes"); out.flush(); out.close(); }