在写一个AJAX小实例的时候,发现一个奇怪的问题:
<
htmlxmlns
=
"
http://www.w3.org/1999/xhtml
"
>
< head >
< title >时间显示 < / title>
< / head>
< body >
< scripttype = " text/javascript " >
function ajaxFunction()
{
var xmlHttp;
if (window.XMLHttpRequest)
{ // codeforallnewbrowsers
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ codeforIE5andIE6 new ActiveXObject( " Microsoft.XMLHTTP " );
}
if (xmlHttp != null )
{
xmlHttp.onreadystatechange = function ()
{
if (xmlHttp.readyState == 4 )
{
document.myForm.time.value = xmlHttp.responseText;
}
}
xmlHttp.open( " GET " , " Test.aspx " , true );
xmlHttp.send( null );
}
}
< / script>
< formname = " myForm " >
用户: < inputtype = " text " name = " username " onkeyup = " ajaxFunction(); " / >
时间: < inputtype = " text " name = " time " / >
< / form>
< / body>
< / html>
< head >
< title >时间显示 < / title>
< / head>
< body >
< scripttype = " text/javascript " >
function ajaxFunction()
{
var xmlHttp;
if (window.XMLHttpRequest)
{ // codeforallnewbrowsers
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ codeforIE5andIE6 new ActiveXObject( " Microsoft.XMLHTTP " );
}
if (xmlHttp != null )
{
xmlHttp.onreadystatechange = function ()
{
if (xmlHttp.readyState == 4 )
{
document.myForm.time.value = xmlHttp.responseText;
}
}
xmlHttp.open( " GET " , " Test.aspx " , true );
xmlHttp.send( null );
}
}
< / script>
< formname = " myForm " >
用户: < inputtype = " text " name = " username " onkeyup = " ajaxFunction(); " / >
时间: < inputtype = " text " name = " time " / >
< / form>
< / body>
< / html>
Test.aspx的c#代码为:
protected
void
Page_Load(objectsender,EventArgse)
{
Response.Expires = - 1 ;
Response.Write(DateTime.Now.ToString()); // 输出当前时间
}
{
Response.Expires = - 1 ;
Response.Write(DateTime.Now.ToString()); // 输出当前时间
}
通过xmlHttp.responseText返回的时间却是:当前时间和Test.aspx页面的HTML代码。
有人说,要清除Test.aspx页面上的所有HTML代码,这样返回的确实只有当前时间了。
偶然发现,在Response.Write后面加一句:Response.End(); 就能避免返回Test.aspx页面的HTML代码了,而无需清除页面的HTML。
Response.End();
}