Ajax简单的来说就是一个JavaScript的异步请求,用来获取后台服务端的数据。
在JS中来实现Ajax主要类就是XMLHttpRequest。
它的使用一般分为四个步骤:
1.创建XMLHttpRequest对象;2.准备发送网络请求;3.开始发送网络请求;4.指定回调函数;

一.GET请求

  1. //1.创建XMLHttpRequest对象
  2. var xhr = null;
  3. if(window.XMLHttpRequest){
  4. xhr = new XMLHttpRequest();
  5. }else{
  6. //兼容低版本IE浏览器
  7. xhr = new ActiveXObject('Microsoft.XMLHTTP')
  8. }
  9. //2.准备发送,true代表异步,false代表同步。如果不设置默认为异步
  10. xhr.open("get","url",true);
  11. //3.执行发送
  12. xhr.send(null);
  13. //4.设置回调函数
  14. xhr.onreadystatechange = function(){
  15. if(xhr.readyState == 4){
  16. if(xhr.status == 200){
  17. var result = xhr.responseText;
  18. console.log(result);
  19. }
  20. }
  21. };

二.POST请求

  1. //1.创建XMLHttpRequest对象
  2. var xhr = null;
  3. if(window.XMLHttpRequest){
  4. xhr = new XMLHttpRequest();
  5. }else{
  6. //兼容低版本IE浏览器
  7. xhr = new ActiveXObject('Microsoft.XMLHTTP')
  8. }
  9. //2.准备发送,true代表异步,false代表同步。如果不设置默认为异步
  10. xhr.open("post","url",true);
  11. //3.执行发送
  12. var param = "请求参数" //对于post请求,应将参数放入请求体中
  13. xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//设置xhr请求头信息,仅限于post请求使用
  14. xhr.send(param);
  15. //4.设置回调函数
  16. xhr.onreadystatechange = function(){
  17. if(xhr.readyState == 4){
  18. if(xhr.status == 200){
  19. var result = xhr.responseText;
  20. console.log(result);
  21. }
  22. }
  23. };

PS : 如果不需要兼容低版本浏览器(IE6,7,8),可以直接使用 var xhr = new XMLHttpRequest()

三.xhr.readyState参数含义

参数值 含义
xhr.readyState=0 表示xhr对象创建完成
xhr.readyState=1 表示已经发送了请求
xhr.readyState=2 浏览器已经收到了服务器响应的数据
xhr.readyState=3 正在解析数据
xhr.readyState=4 数据解析完成,可正常使用。实际开发中通常只关心此状态

四.xhr.status常见状态码

参数值 含义
xhr.status=200 表示响应成功
xhr.status=404 表示没有找到请求的资源
xhr.status=500 服务器端错误