ajax返回xml并解析

//创建xmlrequest对象


function getXMLHttpRequestObject(){
  
 try{
  xmlRequest = new XMLHttpRequest(); //Firefox ,safari
 }catch(e){
  //IE
  try{
   xmlRequest = new ActiveXObject("Msxml2.XMLHTTP");
  }catch(e){
      xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
 return xmlRequest;
}

//发送ajax请求

 

function sendAjaxRequest(url,callBackMethod){
 xmlRequest = getXMLHttpRequestObject();
 xmlRequest.onreadystatechange = callBackMethod;
 xmlRequest.open("post",url,true);
 xmlRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
 xmlRequest.send(url);
 return true;

 

//ajax调用函数

function  getTotalList1(product){
    url = "../sparepart/get.action?product="+product;
    if(!sendAjaxRequest(url,dataChange))
    return;
  }
 

//状态改变时调用的函数
  function  dataChange(){
     if(xmlRequest.readyState==4){
   if(xmlRequest.status==200){
    parseXML(xmlRequest.responseXML);//已经可以正常接受数据
   }else { //页面不正常
                window.alert("您所请求的页面有异常。");
            }
  }
  }

//解析返回的xml
  function  parseXML(xml){
     var  infos = xml.getElementsByTagName("info");
      for(var i=0;i       var  name = infos[i].getElementsByTagName('name')[0].firstChild.data;
       var issn = infos[i].getElementsByTagName('issn')[0].firstChild.data;
       var id = infos[i].getElementsByTagName('id')[0].firstChild.data;
       doAppend(name,issn,id);      
      }    
  }

 

//jsp界面此处注意out变量类型

<%@ page  contentType="text/xml; charset=UTF-8" language="java" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="css.sparepart.bean.Info" %>
<%
 response.setCharacterEncoding("utf-8");
 response.setContentType("text/xml;charset=utf-8");
 List  list = (ArrayList)request.getAttribute("sanlist");
 PrintWriter out1 = response.getWriter();
 out1.println("");
 out1.println("");
 for(int i=0;i   Info  info= (Info)list.get(i);
   out1.println("");
   out1.println(""+info.getName()+"");
   out1.println(""+info.getIssn()+"");
   out1.println(""+info.getId()+"");
   out1.println("
");
 }
  out1.println("
");
%>

你可能感兴趣的:(ajax)