This article analyzes the interaction between Ajax and servlet in the form of examples, and there are more detailed comments in the code to help everyone read and understand. The specific implementation method is as follows:
1.JavaScript part
var req; /*Send parameters to ajaxServlet through asynchronous transmission of XMLHTTP and return qualified XML documents*/ var url; function getResult() { var f=document.getElementById("form_pub"); var key=fsoptions[fsselectedIndex]. text; //Get a reference to the text in select if (window.XMLHttpRequest) { req = new XMLHttpRequest(); url = "ajaxServlet?action="+key+"&bm=UTF-8"; }else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); url = "ajaxServlet?action= "+key+"&bm=gbk"; } if(req) { req.open("GET",url, true); req.setRequestHeader("Content-Type", "text/html;charset=UTF-8"); //If the header is not set here, it will cause firfox to send data incorrectly, and the parameters received by the servlet will be garbled. In IE Medium normal req.onreadystatechange = complete; req.send(null); //req.setRequestHeader("Content-Type", "text/xml; charset=UTF-8"); } } /*Analyze the returned XML document*/ function complete(){ if (req.readyState == 4) { if (req.status == 200) { var items=document.getElementById ("belong"); //The following is the XML document returned by parsing var xmlDoc = req.responseXML; var Node=xmlDoc.getElementsByTagName("type_name"); //var str=new Array(); var str=null; //Clear working items.innerHTML=""; //Delete all content in a select for(var i =0;i<Node.length;i++) { str=Node[i]; //alert(str.childNodes[0].nodeValue); var objectOption=document.createElement("option"); items.options.add(objectOption); //firfox does not support innerText and must be replaced by textContent if (window.ActiveXObject) {objectOption.innerText=str.childNodes[0].nodeValue; } else {objectOption.textContent=str.childNodes[0].nodeValue;} } } } }
2.Servlet side:
package ajax;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 ;import Data_GetConn.GetConn;//This package is written by myself. To obtain the reference to mysql, import java.sql.*;//This package must have it! ! public class ajaxServlet extends HttpServlet{ //private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";//It is best to use UTF-8 for encoding here public void init() throws ServletException{} public void doGet (HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml; charset=UTF-8"); //The following two sentences are to cancel the local cache response.setHeader("Cache-Control", "no-cache"); response.setHeader(" Pragma", "no-cache"); PrintWriter out = response.getWriter(); String action = request.getParameter("action"); String bm = request.getParameter("bm"); if(("gbk").equals(bm)) { action=new String(action.getBytes("ISO-8859-1"),"gbk");//will get The data is re-encoded with gbk! (Thanks to Teacher Dong Wei) } else { action=new String(action.getBytes("ISO-8859-1"),"gbk"); } try { GetConn wq=new GetConn(); Connection con=wq.getCon( ); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select items from class where main='"+action+"'"); StringBuffer sb = new StringBuffer(); sb.append("<type>"); while(rs.next()) { sb.append("<type_name>"+rs .getString(1)+"</type_name>"); } //sb.append("<type_name>"+action+"</type_name>"); sb.append("</type>"); out.write(sb.toString());//Note the stream output to jsp here, the interception method out.close(); stmt.close() in the script ; con.close(); } catch(Exception ex) { } }}