要想把请求发送到服务器,我们就需要使用 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>下一节介绍 "time.asp" 的脚本,这样我们完整的 ajax 应用程序就搞定了。
新闻热点
疑难解答
图片精选