AJAX读取XML赋值给下拉列表

servlet文件

package com.ajax_xml;

import java.io.File;
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 javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class getXml extends HttpServlet {

 /**
  * Constructor of the object.
  */
 public getXml() {
  super();
 }

 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }

 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request
  *            the request send by the client to the server
  * @param response
  *            the response send by the server to the client
  * @throws ServletException
  *             if an error occurred
  * @throws IOException
  *             if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("text/xml;charset=GB2312");
  PrintWriter out = response.getWriter();
  request.setCharacterEncoding("GB2312");

  try {
   // 加载XML
   DocumentBuilderFactory dbFactory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder db = dbFactory.newDocumentBuilder();
   // 指定位置

   Document document = db.parse("d:/ajaxXml.xml");
   // 获得节点集合
   NodeList nodes = document.getElementsByTagName("info");
   out.println("<?xml version='1.0' encoding='GB2312'?>");
   out.println("<placename>");
   // 循环打印节点下的值
   for (int i = 0; i < nodes.getLength(); i++) {
    // 获得节点
    Element element = (Element) nodes.item(i);
    out.println("<info>");
    out.println("<name>"
      + element.getElementsByTagName("name").item(0)
        .getFirstChild().getNodeValue() + "</name>");
    out.println("</info>");
   }
   out.println("</placename>");
  } catch (Exception e) {
   // 获得打印所有异常
   e.printStackTrace();
  }
  out.close();
 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to
  * post.
  *
  * @param request
  *            the request send by the client to the server
  * @param response
  *            the response send by the server to the client
  * @throws ServletException
  *             if an error occurred
  * @throws IOException
  *             if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  doGet(request, response);
 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException
  *             if an error occure
  */
 public void init() throws ServletException {
  // Put your code here
 }

}

 

 

jsp文件

 

 

<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://"
   + request.getServerName() + ":" + request.getServerPort()
   + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <base href="<%=basePath%>">

  <title>My JSP 'index.jsp' starting page</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
  <script type="text/javascript">
 //创建XMLHttpRequest对象
    var xmlhttp
 function ajaxSubmit(){
    try{
        xmlhttp = new XMLHttpRequest();
    }catch(e){
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //创建请求结果处理程序
    xmlhttp.onreadystatechange = processResponse;
    //打开连接,true代表异步提交
    xmlhttp.open("GET","servlet/getXml",true);
    //发送数据
    xmlhttp.send(null);
 }
 function processResponse(){
        if(4 == xmlhttp.readyState){
            if(200 == xmlhttp.status){
             var xmlDom = xmlhttp.responseXML;
             var source=new ActiveXObject("Msxml2.DOMDocument");  
    source.async=false;  
    source.load(xmlDom)     
    var ItemN = source.getElementsByTagName("info");
    var j = ItemN.length;//获取item节点个数
    for(i=0;i<j;i++){
     var select=window.document.getElementById("select").options[i]=new Option(ItemN[i].selectSingleNode("name").text);
<%--     window.alert(ItemN[i].selectSingleNode("name").text);--%>//打印所有的信息
    }
            }else{
                alert("error");
            }
        }
    }
 </script>
 </head>

 <body>
 <button οnclick="ajaxSubmit()"></button>
  <select name="select" id="select">
  </select>

 </body>
</html>

XML文件(必须放在D:下)

<?xml version="1.0" encoding="utf-8"?>
<placename>
 <info>
  <name>沈阳</name>
 </info>
 <info>
  <name>大连</name>
 </info>
 <info>
  <name>北京</name>
 </info>
 <info>
  <name>日本</name>
 </info>
 <info>
  <name>湖南</name>
 </info>
 <info>
  <name>天津</name>
 </info>
 <info>
  <name>香港</name>
 </info>
 <info>
  <name>美国</name>
 </info>
</placename>

 

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值