当前位置: 首页 > 图文教程 > 网络编程 > Javascript > AJAX教程(6):AJAX - 请求服务器

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 AJAX教程(6):AJAX - 请求服务器


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 307 ::
收藏到网摘: n/a

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>

下一节介绍 "time.asp" 的脚本,这样我们完整的 AJAX 应用程序就搞定了。