|
楼主 |
发表于 2009-10-13 15:21:50
|
显示全部楼层
AJAX - 向服务器发送一个请求要想把请求发送到服务器,我们就需要使用 open() 方法和 send() 方法。
open() 方法需要三个参数。第一个参数定义发送请求所使用的方法(GET 还是 POST)。第二个参数规定服务器端脚本的 URL。第三个参数规定应当对请求进行异步地处理。
send() 方法可将请求送往服务器。如果我们假设 HTML 文件和 ASP 文件位于相同的目录,那么代码是这样的:
- xmlHttp.open("GET","time.asp",true);
- xmlHttp.send(null);
复制代码
现在,我们必须决定何时执行 AJAX 函数。当用户在用户名文本框中键入某些内容时,我们会令函数“在幕后”执行。
- <html>
- <body>
- <script type="text/javascript">
- function ajaxFunction()
- {
- var 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>
复制代码 |
|