• 从服务器获取信息的方式


    常用的从服务器获取信息的方式有三种:XmlHttpRequest、动态脚本注入和Multipart XHR

    1、XmlHttpRequest

     let xhr = new XMLHttpRequest();
    // 请求成功回调函数
    xhr.onload = e => {
        console.log('request success');
    };
    // 请求结束
    xhr.onloadend = e => {
        console.log('request loadend');
    };
    // 请求出错
    xhr.onerror = e => {
        console.log('request error');
    };
    // 请求超时
    xhr.ontimeout = e => {
        console.log('request timeout');
    };
    // 请求回调函数.XMLHttpRequest标准又分为Level 1和Level 2,这是Level 1和的回调处理方式
    // xhr.onreadystatechange = () => {
    //  if (xhr.readyState !== 4) {
    //  return;
    //  }
    //  const status = xhr.status;
    //  if ((status >= 200 && status < 300) || status === 304) {
    //  console.log('request success');
    //  } else {
    //  console.log('request error');
    //  }
    //  };
    
    xhr.timeout = 0; // 设置超时时间,0表示永不超时
    // 初始化请求
    xhr.open('GET/POST/DELETE/...', '/url', true || false);
    // 设置期望的返回数据类型 'json' 'text' 'document' ...
    xhr.responseType = '';
    // 设置请求头
    xhr.setRequestHeader('', '');
    // 发送请求
    xhr.send(null || new FormData || 'a=1&b=2' || 'json字符串');
    View Code

    2、动态脚本注入

    var scriptElement = document.createElement('script');
    scriptElement.src = 'http://any-domain.com/javascript/lib.js';
    document.getElementsByTagName('head')[0].appendChild(scriptElement);
    
    function jsonCallback(jsonString){
       var data = eval('(' + jsonString + ')');
      //do something
    }
    
    lib.js 里的内容示例:
    jsonCallback({"status":1,"name":"测试"});
    View Code

    3、Multipart XHR

     通过发送一次XmlHttpRequest请求,从服务器获取到多个资源信息,根据约定的分隔符进行分离,进而呈现对应的资源信息。这种方式可以避开浏览器对http请求数量的限制

  • 相关阅读:
    eclipse开发环境搭建
    如何在不知道密码的情况下卸载趋势防毒墙网络版
    PB 将游标中的数据存到数组中
    SQL Server 系统表使用举例
    row_number() over(partition by a order by b desc) rn 用法
    C#选中当前一行,判断是否为空(顺序)
    C#DataTable与Grid的差别
    C#采番的前端与SQL的写法
    Grid的check
    Combox的去重方法
  • 原文地址:https://www.cnblogs.com/lianjinzhe/p/13332129.html
Copyright © 2020-2023  润新知