AJAX 请求步骤

2018-06-22  本文已影响20人  那颗星_fcaf

AJAX 是什么

ajax 是一种异步请求数据的技术,对于提高用户体验度和程序性能有很大的帮助。

AJAX 请求步骤

  1. 创建 ajax 核心对象 XMLHttpRequest
let xmlHttp;
if (window.XMLHttpRequest) {
  xmlHttp = new XMLHttpRequest;
} else {
  xmlHttp = new ActiveXObject('Microsoft.XMLHttp'); // IE5、6执行此代码
}
  1. 向服务器发送请求
xmlHttp.open(method, url, async);
xmlHttp.send();

注意:

xmlHttp.open('POST', 'ajax+test.html', true);
xmlHttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xmlHttp.send('fname=Herry&lname=Ford');
  1. 服务器详情处理
    responseText 获得字符串形式的相应数据
    responseXML 获得 XML 像是的相应数据
    3.1 同步处理

    xmlHttp.open('GET', 'http://www.we.com/fight/win.php', false);
    xmlHttp.send();
    document.getElsementById('tes-box').innerHtml = xmlHttp.responseText;
    

    3.2 异步处理
    异步处理比较麻烦,要在请求状态事件中处理。

    xmlHttp.onreadystatechange = () => {
      if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
        document.getElementById('text-box').innerHtml = xmlHttp.responseText;
      }
    }
    

    一共有五种请求状态:

    • 0:请求未初始化
    • 1:服务器链接已建立
    • 2:请求已接收
    • 3:请求处理中
    • 4:请求已完成,且相应已就绪 .

    xmlHttp.status:响应状态码。

    • 200:'OK'
    • 304:该资源在上次请求之后没有任何修改(通常用于浏览器的缓存机制,使用 'GET' 请求时尤其需要注意)
    • 403:(禁止)服务器拒绝请求
    • 404:(未找到)服务器找不到请求的网页
    • 408:(请求超时)服务器等候请求时发生超时
    • 500:(服务器内部错误)服务器遇到错误,无法完成请求
上一篇 下一篇

猜你喜欢

热点阅读