Ajax example

READYSTATE

The readyState property indicates the current state of an Ajax request. Its value is numerical:

  • 0 Uninitialized. The open method hasn’t been called yet.
  • 1 Loading. The open method has been called, but the send method hasn’t.
  • 2 Loaded. The send method has been called. The request has begun
  • 3 Interactive. The server is in the process of sending a response.
  • 4 Complete. The server has finished sending a response.

STATUS

  • I’m sure you’re familiar with the 404 status code, which translates to “Not Found.”
  • Some other codes are 403 for “Forbidden,” and 500 for “Internal Server Error.”
  • The most common status code is 200, which means “OK.” 
  • A value of 304 translates as “Not Modified.” The server sometimes returns this response if a browser performs what’s known as a conditional GET request. The Opera browser uses conditional GET requests. In this situation, the server may return a response of 304, indicating that the document hasn’t changed since it was last requested, so the browser can safely use a cached version.
  • if 0, means ok, and the request url is local.

HTML

 
  
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
>
< html >
< head >
< title > Using XMLHttpRequest </ title >
< script type ="text/javascript" src ="ajaxtest.js" ></ script >
</ head >
< body >
< p >
< a href ="message.txt" onclick ="grabFile(this.href); return false;" >
Click here to see the contents of a text file
</ a >
</ p >
</ body >
</ html >

JavaScript Codes

 
  
function getHTTPObject() {
var xhr = false ;
if (window.XMLHttpRequest) {
xhr
= new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
xhr
= new ActiveXObject( " Msxml2.XMLHTTP " );
}
catch (e) {
try {
xhr
= new ActiveXObject( " Microsoft.XMLHTTP " );
}
catch (e) {
xhr
= false ;
}
}
}
return xhr;
}

function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange
= function () {
displayResponse(request);
};
request.open(
" GET " , file, true );
request.send(
null );
}
}

function displayResponse(request) {
if (request.readyState == 4 ) {
if (request.status == 200 || request.status == 304 ) {
alert(request.responseText);
}
}
}

转载于:https://www.cnblogs.com/chrix/archive/2011/05/20/2051883.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值