• 原生Ajax实现异步交互


    1. 实现Ajax主要依靠XMLHttpRequest对象,所以首先要创建XMLHttpRequest对象
      function getXhr(){
         var xhr = null;
         if(window.XMLHttpRequest){
      //高版本浏览器
              xhr = new XMLHttpRequest;
         }else{
      //IE低版本浏览器
             xhr = new ActiveXObject("Microsoft.XMLHttp");
         }
         return xhr;
      }
      var xhr = getXhr();
    2. 使用open方法与服务器建立连接
      open(method, url, async);
      xhr.open('post', 'data_montor.php', true);
      xhr.open('get', 'data_montor.php?user = name', true);
      //method 表示get/post //url 表示请求的地址 //async 表示同步还是异步,async = true 异步(默认) //若将async设置为false,官方认为XMLHttpRequest就是实现异步交互的会进行警告
      //如果是get方法请求参数应跟在url之后,而不是通过send发送
    3. 客户端向服务器发送请求
      send(请求参数)方法
      //请求参数的格式   key = value
      xhr.send('user = xinyue')
      //注意:如果使用get方法,send不能向服务器发送请求数据,但是也不能忽略
      //需要写成 send(NULL); 然后请求数据应放在open方法中的Url之后
      //(详见上一步)
    4. 客户端接受服务器端的响应:使用onreadyStatechange 时间监听服务器的通信状态
      xhr . onreadystatechange  = function(){
          if(xhr.readyState == 4){
              if(xhr. status == 200){
                  var data = xhr.responseText;
      //HTML格式使用responseText接收服务器端的相应数据,解析过程比较复杂(拆串),拆串拼串极易出错
                  console.log(data);
              }
         }
      }

      readyState 得服务器端当前通信状态 : 
              0 服务器端尚未初始化
              1 正在发送请求
              2  请求完成
              3  请求成功,客户端正在接收服务器端的数据
              4  响应完成
      status :  1XX 信息类
                    2XX 成功
                    3XX 重定向
                    4XX 客户端错误
                    5XX 服务器端错误
                                                     

  • 相关阅读:
    外媒评Mate 10 Pro:智慧拍照惊人,续航能力卓越
    pv(PageView)的解释
    pv(PageView)的解释
    pv(PageView)的解释
    pv(PageView)的解释
    对包含HttpContext.Current.Cache的代码进行单元测试
    读取excel模板填充数据 并合并相同文本单元格
    css
    Aragon:以太坊上的去中心化自治组织管理应用
    Futarchy: 对价值投票,对赌信念
  • 原文地址:https://www.cnblogs.com/Auyuer/p/8532327.html
Copyright © 2020-2023  润新知