您的位置:首页 > 其它

AJAX - 向服务器发送一个请求

2010-03-22 10:43 225 查看

要想把请求发送到服务器,我们就需要使用 open() 方法和 send() 方法。

open() 方法需要三个参数。第一个参数定义发送请求所使用的方法(GET 还是 POST)。第二个参数规定服务器端脚本的 URL。第三个参数规定应当对请求进行异步地处理。

send() 方法可将请求送往服务器。如果我们假设 HTML 文件和 ASP 文件位于相同的目录,那么代码是这样的:
xmlHttp.[code]open
("GET","time.asp",true);
xmlHttp.
send
(null);
[/code]
现在,我们必须决定何时执行 AJAX 函数。当用户在用户名文本框中键入某些内容时,我们会令函数“在幕后”执行。
<html>
<body>

<script type="text/javascript">

function ajaxFunction()
{
var [code]xmlHttp
;

try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();

}
catch (e)
{

// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

}
catch (e)
{

try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

}
catch (e)
{
alert("您的浏览器不支持AJAX!");
return false;
}
}
}

xmlHttp.
onreadystatechange
=function()
{
if(xmlHttp.
readyState
==4)
{
document.myForm.time.value=xmlHttp.
responseText
;
}
}
xmlHttp.
open("GET","time.asp",true)
;
xmlHttp.
send(null)
;

}
</script>

<form name="myForm">
用户: <input type="text" name="username"
onkeyup="ajaxFunction();"
/>
时间: <input type="text" name="time" />
</form>

</body>
</html>
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: