在写一个AJAX小实例的时候,发现一个奇怪的问题:
<
html xmlns
=
"
http://www.w3.org/1999/xhtml
"
>
< head >
< title >时间显示 < / title>
< / head>
< body >
< script type = " text/javascript " >
function ajaxFunction()
{
var xmlHttp;
if (window.XMLHttpRequest)
{ // code for all new browsers
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // code for IE5 and IE6
xmlHttp = 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>
< form name = " myForm " >
用户: < input type = " text " name = " username " onkeyup = " ajaxFunction(); " / >
时间: < input type = " text " name = " time " / >
< / form>
< / body>
< / html>
< head >
< title >时间显示 < / title>
< / head>
< body >
< script type = " text/javascript " >
function ajaxFunction()
{
var xmlHttp;
if (window.XMLHttpRequest)
{ // code for all new browsers
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // code for IE5 and IE6
xmlHttp = 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>
< form name = " myForm " >
用户: < input type = " text " name = " username " onkeyup = " ajaxFunction(); " / >
时间: < input type = " text " name = " time " / >
< / form>
< / body>
< / html>
Test.aspx的c#代码为:
protected
void
Page_Load(object sender, EventArgs e)
{
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。
protected
void
Page_Load(object sender, EventArgs e)
{
Response.Expires = - 1 ;
Response.Write(DateTime.Now.ToString()); // 输出当前时间
Response.End();
}
{
Response.Expires = - 1 ;
Response.Write(DateTime.Now.ToString()); // 输出当前时间
Response.End();
}
Response.End() 使 Web 服务器停止处理脚本并返回当前结果。文件中剩余的内容将不被处理。