ajax(一)
XMLHttpRequest对象的属性:
1.onreadystatechange 属性
2.readyState 属性
3.responseText 属性
onreadystatechange 属性
onreadystatechange 属性存有处理服务器响应的函数。下面的代码定义一个空的函数,可同时对 onreadystatechange 属性进行设置:
xmlHttp.onreadystatechange=function()
{
// 我们需要在这里写一些代码
}
readyState 属性
readyState 属性存有服务器响应的状态信息。每当 readyState 改变时,onreadystatechange 函数就会被执行。
这是 readyState 属性可能的值:
| 状态 | 描述 |
|---|---|
| 0 | 请求未初始化(在调用 open() 之前) |
| 1 | 请求已提出(调用 send() 之前) |
| 2 | 请求已发送(这里通常可以从响应得到内容头部) |
| 3 | 请求处理中(响应中通常有部分数据可用,但是服务器还没有完成响应) |
| 4 | 请求已完成(可以访问服务器响应并使用它) |
我们要向这个 onreadystatechange 函数添加一条 If 语句,来测试我们的响应是否已完成(意味着可获得数据):
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
// 从服务器的response获得数据
}
}
responseText 属性
可以通过 responseText 属性来取回由服务器返回的数据。
在我们的代码中,我们将把时间文本框的值设置为等于 responseText:
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
AJAX - 向服务器发送请求
open() 方法和 send() 方法。
open() 方法需要三个参数。第一个参数定义发送请求所使用的方法(GET 还是 POST)。第二个参数规定服务器端脚本的 URL。第三个参数规定应当对请求进行异步地处理。
send() 方法可将请求送往服务器。如果我们假设 HTML 文件和 ASP 文件位于相同的目录,那么代码是这样的:
xmlHttp.open("GET","time.asp",true); xmlHttp.send(null);
<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
//IE 浏览器使用 ActiveXObject,而其他的浏览器使用名为 XMLHttpRequest 的 JavaScript 内建对象。
try
{
// Firefox, Opera 8.0+, Safari -- XMLHttpRequest
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
//IE 6.0+ --ActiveXObject("Msxml2.XMLHTTP")
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
//IE 5.5+ --ActiveXObject("Microsoft.XMLHTTP")
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
<% response.expires=-1 response.write(time) %>
浙公网安备 33010602011771号