XMLHttpRequest 对象获取服务端数据

我们可以使用 XMLHttpRequest对象的ResponseXML属性获取服务器端数据。需要注意的是,ASP.NET 文件 index.aspx 的contentType 必须是 text/xml ,XMLHttpRequest.ResponseXML属性才能解析成XML文件流。

html 文件
 1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 2<html>
 3<head>
 4<title></title>
 5<script language="javascript" src="JScript1.js"></script>
 6</head>
 7<body>
 8    <input type="text" id="InputID">
 9    <input type="button" value="OK" onclick="ChangeValue();"> <br>
10    <div id="showHot"></div>
11</body>
12</html>
13

JS 文件
 1function ajaxRequest(){
 2    Ajax = false;
 3    try{
 4       Ajax = new XMLHttpRequest();
 5    }
catch(ee){
 6       try{
 7               Ajax = new ActiveXObject("Msxml.XMLHTTP");        
 8       }
catch(e){
 9               try{
10               Ajax = new ActiveXObject("Msxml.XMLHTTP");        
11               }
catch(e){
12               try{
13                       Ajax = new ActiveXObject("Microsoft.XMLHTTP");                
14               }
catch(E){
15                   Ajax = false;
16               }

17               }

18       }

19     }

20}

21
22function getAjaxValue(strUserID){    
23    ajaxRequest();
24    if(!Ajax){
25        alert("Ajax its not working");
26        return;
27    }

28    var xmlValue = new String();
29    Ajax.open("GET""index.aspx?userid="+strUserID,false)
30    Ajax.send(null);
31    var xmldoc = Ajax.responseXML.getElementsByTagName("div");
32    if(xmldoc.length > 0)
33    {
34        for(var i=0;i<xmldoc.length;i++)
35        {
36            xmlValue += (i+1+""+ xmldoc[i].firstChild.data + "<br>";
37        }

38    }

39    
40    return xmlValue;
41}

42
43function ChangeValue()
44{
45    var strvalue = "";
46    strvalue = document.getElementById("InputID").value;
47    var setValue = document.getElementById("showHot");
48    setValue.innerHTML = getAjaxValue(strvalue);
49}
posted @ 2007-04-29 14:06  祝金峰  阅读(923)  评论(0编辑  收藏  举报