• XMLHttpRequest原生方法


    时间久了,在工作中会有很多方法和见解。

    随着时间的推移,慢慢的写的代码越来越多,封装分方法也越来越多,为的是方便后续工作,加快开发效率!

    与此同时,我们会相应的去找一些插件,来代替我们在开发过程中执行一些功能,比如jQuery封装的 xhr Ajax请求方法。

     1 <!DOCTYPE html>
     2 <html>
     3     <head>
     4         <meta charset="utf-8">
     5         <title>XMLHttpRequest原生封装</title>
     6     </head>
     7     <body>
     8         <script type="text/javascript">
     9             // Ajax封装
    10             var xhr;
    11             if (window.XMLHttpRequest) { // Mozilla,Safari
    12                 xhr = new XMLHttpRequest();
    13             } else if (window.ActiveXObject) { // IE
    14                 try {
    15                     xhr = new ActiveXObject('Msxml2.XMLHTTP');
    16                 } catch (e) {
    17                     try {
    18                         xhr = new ActiveXObject('Microsoft.XMLHTTP'); // IE5,IE6
    19                     } catch (e) {}
    20                 }
    21             }
    22             // get 请求
    23             xhr.open('GET', 'url', true);
    24             xhr.send();
    25 
    26 
    27             /* POST 请求封装 */
    28             var xhr;
    29             if (window.XMLHttpRequest) {
    30                 xhr = new XMLHttpRequest();
    31             } else if (window.ActiveXObject) {
    32                 try {
    33                     xhr = new ActiveXObject('Msml2.XMLHTTP');
    34                 } catch (e) {
    35                     try {
    36                         xhr = new ActiveXObject('Microsoft.XMLHTTP');
    37                     } catch (e) {}
    38                 }
    39             }
    40             if (xhr) {
    41                 xhr.onreadystatechange = onReadyStateChange;
    42                 xhr.open('POST', '/api', true);
    43                 // 设置Content-Type 为application/x-www-form-urlencoded
    44                 // 以表单的形式传递数据
    45                 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    46                 xhr.send('username=admin&password=root');
    47             }
    48 
    49             // onReadyStateChange 方法
    50             function onReadyStateChange() {
    51                 // 该函数会被调用四次
    52                 if (xhr.readyState === 4 && xhr.status === 200) {
    53                     console.log('发送成功!');
    54                 } else {
    55                     console.log('发送失败!')
    56                 }
    57             }
    58         </script>
    59     </body>
    60 </html>

    JavaScript原生请求数据的方法,使用的是XMLHttpRequest方法,但是为了兼容微软的低版本 IE 浏览器,我们需要使用XMLActiveXObject()方法来实现低版本的IE浏览器的数据交互,Get和Post请求方式,还是存在一定的区别的,如:参数的个数和类型的不同,代表的含义也不一样。判断的状态也不相同!

  • 相关阅读:
    男人要知道的40条忠告
    利用xtraBackup实现不停master服务做主从同步
    MY SQL 知识
    房价与阶级
    SQL Server数据库级别触发器
    mysql 5.7开启并行复制
    SQL Server 查出未提交事务(长事务)SQL
    开源数据集
    telnet
    Zend Studio使用综述
  • 原文地址:https://www.cnblogs.com/zxk5211/p/web_11.html
Copyright © 2020-2023  润新知