日期:2014-05-16  浏览次数:20492 次

Ajax 抓页面
引用




<html>
<head>
  <title>AJAX.html</title>
</head>
<script type="text/javascript">
/*通过异步传输XMLHTTP发送参数到ajaxServlet,返回符合条件的XML文档*/
function getResult(){
  var url = "ajaxServlet?action=send";
  if (window.XMLHttpRequest){
   req = new XMLHttpRequest();
  }else if (window.ActiveXObject)
  {
   req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if(req)
  {
   req.open("GET",url, true);
   req.onreadystatechange = complete;
   req.send(null);
  }
}
/*分析返回的XML文档*/
function complete(){
  if (req.readyState == 4)
  {
   if (req.status == 200){
//也可以用var date=req.responseText;直接取得服务器端的输出
//通过标签的方式取值
    var type = req.responseXML.getElementsByTagName("type_name");
    var str=new Array();
    for(var i=0;i<type.length;i++){
     str[i]=type[i].firstChild.data;
     document.all['td'].innerHTML+=str[i]+"<BR>";
    }
   }
  }
}
</script>
<body onLoad="getResult()">
  <table width="80%" border="0" cellspacing="0" cellpadding="0">
   <tr>
    <td id="td">
    </td>
   </tr>
  </table>
</body>
</html>
---------------------------------ajaxServlet.java-----------------------------------------------------
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;

public class ajaxServlet extends HttpServlet{
private static final String CONTENT_TYPE = "text/xml; charset=gb2312";
public void init() throws ServletException{}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
  response.setContentType(CONTENT_TYPE);
  PrintWriter out = response.getWriter();
  String action = request.getParameter("action");
  if (("send").equals(action))
  {
   StringBuffer sb = new StringBuffer("<type>");
   sb.append("<type_name>AA</type_name>");
   sb.append("<type_name>BB</type_name>");
   sb.append("<type_name>CC</type_name>");
   sb.append("<type_name>DD</type_name>");
   sb.append("</type>");
   out.write(sb.toString());
   out.close();
  }
}
}