本文以實例形式剖析了Ajax與servlet的交互,且程式碼中有較為詳細的註釋,以幫助大家閱讀理解。具體的實作方法如下:
1.JavaScript部分
var req; /*透過非同步傳輸XMLHTTP傳送參數到ajaxServlet,傳回符合條件的XML文件*/ var url; function getResult() { var f=document.getElementById("form_pub"); var key=fsoptions[fsselectedIndex]. 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.HttpServletRequestReimport 4xlet. ;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{} publicoid 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) { } }}