欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

实例解读Ajax与servlet交互的方法

程序员文章站 2024-02-27 19:38:27
本文以实例形式剖析了ajax与servlet的交互,并且代码中有较为详细的注释,以帮助大家阅读理解。具体的实现方法如下: 1.javascript部分 var...

本文以实例形式剖析了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)
  {
     
  }
 
 }
}