AJAX心得

持续补充...

AJAX的核心是异步对象XMLHttpRequest对象,一个具有程序接口的JavaScript对象,能够使用超文本传输协议(HTTP)链接一个服务器。

这是一段标准的AJAX执行代码:

 1 <script type="text/javascript">
 2 function loadXMLDoc()
 3 {
 4 var xmlhttp;
 5 if (window.XMLHttpRequest)//用兼容性的方法获取xmlhttprRequest对象
 6   {// IE7+、Firefox、Chrome、Opera、Safari支持的方法
 7   xmlhttp=new XMLHttpRequest();
 8   }
 9 else
10   {// 兼容IE6, IE5
11   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
12   }
13 xmlhttp.onreadystatechange=function()
14   {
15   if (xmlhttp.readyState==4 && xmlhttp.status==200)
16     {
17     alert(1);
18     }
19   }
20 xmlhttp.open("GET","test/myajax.php",true);
21 xmlhttp.send();
22 }
23 </script>

整个过程分为:

  1. 创建对象var xmlhttp = new XMLHtttpRequest()
  2. 设置请求的参数,url等数据   xmlhttp.open('请求的方法','请求的url','异步还是同步');
  3. 发送请求  xmlhttp.send();
  4. 注册事件  
    1 xmlhttp.onreadystatechange = function() {
    2    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    3      alert(1);
    4    }
    5 }

    onreadstatechange事件是状态改变时调用,有两个属性:

    • readyState属性是储存XMLHttpRequest的状态
      • 0: 请求未初始化
      • 1: 服务器连接已建立
      • 2: 请求已接收
      • 3: 请求处理中
      • 4: 请求已完成,且响应已就绪
    • status属性:200表示执行完毕  404表示未找到  具体查阅http协议

  get方式获取,直接在open()的路径后拼接   post方式在open()和send()之间加入

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
原文地址:https://www.cnblogs.com/missjingjing/p/8689245.html