本文以實例形式剖析了Ajax與servlet的交互,並且代碼中有較為詳細的注釋,以幫助大家閱讀理解。具體的實現方法如下:
1.JavaScript部分
var req; /*通過異步傳輸XMLHTTP發送參數到ajaxServlet,返回符合條件的XML文檔*/ var url; function getResult() { var f=document.getElementById("form_pub"); var key=f.s.options[f.s.selectedIndex].text; //獲取對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"); //這裡如果不設定頭部則會導致 firfox 發送數據錯誤,servlet接受到的參數為亂碼,在IE中正常 req.onreadystatechange = complete; req.send(null); //req.setRequestHeader("Content-Type", "text/xml; charset=UTF-8"); } } /*分析返回的XML文檔*/ function complete(){ if (req.readyState == 4) { if (req.status == 200) { var items=document.getElementById("belong"); //以下為解析返回的XML文檔 var xmlDoc = req.responseXML; var Node=xmlDoc.getElementsByTagName("type_name"); //var str=new Array(); var str=null; //清空工作 items.innerHTML=""; //刪除一個 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不支持innerText必須用textContent代替 if (window.ActiveXObject) {objectOption.innerText=str.childNodes[0].nodeValue;} else {objectOption.textContent=str.childNodes[0].nodeValue;} } } } }
2.servlet端:
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;//這個包是自己寫的為獲取對mysql的引用 import java.sql.*;//這個包必須有!! public class ajaxServlet extends HttpServlet{ //private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";//這裡最好統一用UTF-8進行編碼 public void init() throws ServletException{} public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml; charset=UTF-8"); //以下兩句為取消在本地的緩存 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");//將獲得的數據用gbk從新編碼!(感謝董衛老師) } 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());//注意這裡向jsp輸出的流,在script中的截獲方法 out.close(); stmt.close(); con.close(); } catch(Exception ex) { } } }