Ajax 与 Comet


# Ajax 与 Comet

# 21.1 XmLHttpRequest用法

  • open(type,url,boolean)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if(xhr.readyState == 4) {
    if(xhr.status >=200 && xhr.status< 300 || xhr.status == 304) {
      alert(xhr.responseText)
    } else {
      alert('请求失败:' + xhr.status)
    }

  }
};
xhr.open('get','www.abc.com/a.txt', false)
xhr.timeout = 5000;
xhr.ontimeout = function() {
  alert('请求超时!')
}
xhr.send(null)// 检查状态

  • responseText 作为响应主题被返回的文本
  • responseXML
  • status 响应的HTTP状态
  • statusText HTTP状态说明

readyState 表示请求响应过程的当前活动阶段,可取值:

  • 0 未初始化 上位调用open()方法
  • 1 启动
  • 2 发送 调用open()方法,但上位接收道响应
  • 3 接收 已经接收到部分响应数据
  • 4 完成 已经接收到全部响应数据,而且克一年客户端使用了

# 21.1.2 HTTP头部信息

  • Accept
  • Accept-Charset
  • Accept-Encoding
  • Accept-Language
  • Connection
  • Cookie
  • Host
  • referrer 发送请求的URL

# 21.2 XMLHttpRequest2

# 21.4 跨域资源共享

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    vxhr = new XDomainRequest();
    xhr.open(method, url);
   
  } else {
    xhr = null;
  }
  return xhr;
}
var request = createCORSRequest("get", "http://www.somewhere-else.com/page/");
if (request) {
  request.onload = function () {
    //对 request.responseText 进行处理
  };
  request.send();
}


上次更新: 1/3/2020, 9:54:38 PM