zoukankan      html  css  js  c++  java
  • ajax封装get /post

     1 (function (window) {
     2     function AjaxTool() {}
     3 
     4     AjaxTool.ajaxRequest = function (param, successCallback, failedCallback) {
     5         // 1. 获取参数
     6         var requestType = param['requestType'] || 'get'; // 请求方式
     7         var url = param['url'];  // 请求的路径
     8         var paramObj = param['paramObj'];
     9         var timeOut = param['timeOut'] || 0;
    10 
    11         // 2. 发送请求
    12         var xhr = new XMLHttpRequest();
    13         // 判断
    14         if(requestType.toLowerCase() === 'get'){ // get请求
    15             var codeURL = encodeURI(url + '?' + getStrWithObject(paramObj));
    16             xhr.open('get', codeURL, true);
    17             xhr.send();
    18         }else if(requestType.toLowerCase() === 'post'){ // post请求
    19             var codeParam = encodeURI(getStrWithObject(paramObj));
    20             xhr.open('post', url, true);
    21             // 设置请求头
    22             xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    23             xhr.send(codeParam);
    24         }
    25         // 监听服务器端响应
    26         xhr.addEventListener('readystatechange', function (ev2) {
    27            if(xhr.readyState === 4){
    28                if(xhr.status === 200){
    29                    // 请求成功
    30                    successCallback && successCallback(xhr);
    31                    // 清除定时器
    32                    clearTimeout(timer);
    33                }else {
    34                    // 请求失败
    35                    failedCallback && failedCallback(xhr);
    36                }
    37            }
    38         });
    39 
    40         //  0 代表不限制请求的时间
    41         var timer = null;
    42         if(timeOut > 0){
    43             timer = setTimeout(function () {
    44                 // 取消请求
    45                 xhr.abort();
    46             }, timeOut);
    47         }
    48     };
    49 
    50     /**
    51      *  把对象转换成拼接字符串
    52      * @param {Object}paramObj
    53      */
    54     function getStrWithObject(paramObj) {
    55         var resArr = [];
    56         // 1. 转化对象
    57         for (var key in paramObj) {
    58             var str = key + '=' + paramObj[key];
    59             resArr.push(str);
    60         }
    61         // 2. 拼接时间戳
    62         resArr.push('random=' + getRandomStr());
    63 
    64         // 3. 数组转成字符串
    65         return resArr.join('&');
    66     }
    67 
    68     /**
    69      * 获取随机时间戳
    70      * @returns {number}
    71      */
    72     function getRandomStr() {
    73         return Math.random() + (new Date().getTime());
    74     }
    75 
    76     window.AjaxTool = AjaxTool;
    77 })(window);
     1 <script>
     2     window.addEventListener('load', function (ev) {
     3         var btn = document.getElementById('send');
     4         btn.addEventListener('click', function (ev1) {
     5 
     6             // 1. 获取用户输入的内容
     7             var account = document.getElementById('account').value;
     8             var pwd = document.getElementById('pwd').value;
     9             var paramObj = {
    10                 'account': account,
    11                 'pwd': pwd
    12             };
    13 
    14             var param = {
    15                 'requestType': 'post',
    16                 'url': 'http://localhost:3000/api/five',
    17                 'timeOut': 2000,
    18                 'paramObj': paramObj
    19             }
    20 
    21             // 2. 创建网络请求对象
    22             AjaxTool.ajaxRequest(param, function (xhr) {
    23                 console.log('成功', xhr.responseText);
    24             }, function () {
    25                 console.log('失败')
    26             })
    27         });
    28     });
    29 </script>
  • 相关阅读:
    LeetCode#34 Search for a Range
    Multiplication algorithm
    LeetCode#31 Next Permutation
    Spring boot之Hello World
    spring boot 简介
    分布式-网络通信-线程
    分布式-网络通信-协议
    分布式-架构图
    9.leetcode70-climbing stairs
    8.Leetcode69 Sqrt(x) 笔记
  • 原文地址:https://www.cnblogs.com/zhangzhengyang/p/11223492.html
Copyright © 2011-2022 走看看