通過xmlHttp和ASP的結合,我們可以輕松完成網頁的異步調用。
代碼如下:
1.新建Display.asp(這是前台顯示頁面)
注意xmlhttp.readyState的4個屬性
1:LOADING;2:LOADED;3:INTERACTIVE;4:COMPLETED
<%@ Language=VBScript %>
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
</HEAD>
<script language="javascript">
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
function fnDo(ID)
{
var xmlDom = new ActiveXObject("Msxml2.DOMDocument");
var strURL = "GetInfo.asp?ID=" + ID;
xmlhttp.Open("POST",strURL , true);
xmlhttp.onreadystatechange = fnRun;
xmlhttp.Send(xmlDom);
divTest.innerHTML = "Loading..."
}
//--------------------------------------------------------
function fnRun()
{
var state = xmlhttp.readyState;
var xmlDom = new ActiveXObject("Msxml2.DOMDocument");
if (state == 4)
{
xmlDom.loadXML(xmlhttp.responseXML.xml);
//alert(xmlDom.documentElement.selectSingleNode("//objXML").text)
var getInfo = xmlDom.documentElement.selectSingleNode("//objXML").text;
divTest.innerHTML = getInfo
}
}
</script>
<BODY>
<input type=text id=txtInput>
<input type=button value="異步調用" onclick="fnDo(document.all.txtInput.value)">
<DIV id=divTest></DIV>
<P> </P>
</BODY>
</HTML>
2.在建立GetInfo.asp(這是後台處理頁面)
<%
Dim sID,objResult
sID = Trim(Request("ID"))
'sID = 28
Set objResult = Server.CreateObject("MSXML2.DOMDocument")
objResult.loadXML ("<objXML></objXML>")
'**************************************************************
'**************************************************************
objResult.selectSingleNode("objXML").text = "Get:" & sID
Response.ContentType = "text/xml"
objResult.save (Response)
Response.End
Set objSch = Nothing
Set objResult = Nothing
%>
3.運行Display.asp頁面,在文本框裡輸入內容,點擊按鈕,可以看到Loading的提示,隨後在不刷新頁面的情況下得到了文本框裡的內容。當然你也可以在GetInfo.asp那個頁面裡根據發送的參數做一些復雜的出來,隨後把結果返回出來