zoukankan      html  css  js  c++  java
  • 原生JS封装ajax方法

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4   <meta charset="utf-8">
     5   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
     6   <title>Examples</title>
    10   <script>
    11 
    12     //将对象序列化
    13     function params(data) {
    14       var arg = [];
    15       for (var i in data) {
    16         arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
    17       }
    18       return arr.join('&');
    19     }
    20 
    21     //封装ajax
    22     function ajax(obj) {
    23       //创建xhr对象;
    24       obj.xhr = new XMLHttpRequest();
    25       //后面随机数防止浏览器缓存
    26       obj.url = url + "?rand=" + Math.random();
    27       //序列化对象
    28       obj.data = params(obj.data);
    29       //当是get请求时
    30       if (obj.method = 'get') {
    31         //当前面没设置随机数时
    32         obj.url += obj.url.indexOf('?') == -1 ? '?' +obj.data : '&' + obj.data;
    33       }
    34       //异步调用
    35       if (obj.async == true) {
    36         //监听响应状态
    37         xhr.onreadystatechange = function() {
    38           if (xhr.readyState == 4) {
    39             callback();
    40           }
    41         };
    42       }
    43       //启动HTTP请求
    44       xhr.open(obj.method, obj.url, obj.aysnc);
    45       //当是post请求时
    46       if(obj.method === 'post') {
    47         //模仿表单提交
    48         xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    49         //发送HTTP请求-post
    50         xhr.send(obj.data);
    51       } else {
    52         //发送HTTP请求-get
    53         xhr.send(null);
    54       }
    55       //同步调用
    56       if (obj.async == false) {
    57         callback();
    58       }
    59       //回调函数传参
    60       function callback() {
    61         if (xhr.atatus == 200) {
    62           obj.success(xhr.responseText);
    63         } else {
    64           alert("失败,失败状态码:" + xhr.status);
    65         }
    66       }
    67     }
    68 
    69     document.addEventListener('click', function() {
    70       ajax({
    71         method: 'get',
    72         url: 'demo3.php',
    73         data: {
    74           'name' = 'Lee',
    75           'age' = 100
    76         },
    77         success: function(text) {
    78           alert(text);
    79         },
    80         async = true
    81       });
    82     }, false);
    83   </script>
    84 </head>
    85 <body>
    86     
    87 </body>
    88 </html>
  • 相关阅读:
    makefile之伪目标
    小马哥课堂-统计学-t分布(2)
    小马哥课堂-统计学-t分布
    小马哥课堂-统计学-无偏估计
    matplotlib 添加注释的方式
    leetcode 链表类型题目解题总结
    LeetCode矩阵题型
    fuzzing学习
    linux-2.6.18源码分析笔记---中断
    leetcode math类型题目解题总结
  • 原文地址:https://www.cnblogs.com/chenzechuang/p/6660328.html
Copyright © 2011-2022 走看看