• Ajax 对post 和get 封装


     1 (function (window) {
     2     function AjaxTool() {}
     3 
     4     AjaxTool.ajaxRequest =function (param,sucecessCallBack,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 
    12         var xhr = new XMLHttpRequest();
    13         if(requestType.toLowerCase() ==='get'){
    14         var codeUrl=encodeURI(url + '?' +getStrWithObject(paramObj))
    15             xhr.open('get',codeUrl,true);
    16             xhr.send()
    17         }else if(requestType.toLowerCase() ==='post'){
    18             var codeParam =encodeURI(getStrWithObject(paramObj))
    19             xhr.open('post',url,true);
    20             xhr.send(codeParam)
    21             //post请求
    22         }
    23         // xhr.open('get',url + '?' +getStrWithObject(paramObj),true);
    24         // xhr.send()
    25         //监听服务器响应
    26         xhr.addEventListener("readystatechange", function () {
    27             if(xhr.readyState===4){
    28                 if(xhr.status==200){
    29 
    30                     sucecessCallBack &&  sucecessCallBack(xhr)
    31                     //清除定时器
    32                     clearTimeout(timer)
    33 
    34                 }else{
    35                     failedCallback && failedCallback (xhr)
    36                 }
    37             }
    38         })
    39         /**
    40          *
    41          * 0 代表不限制请求的时间
    42          * **/
    43         var timer =null;
    44         if(timeOut>0){
    45             timer=setTimeout(function () {
    46                 //取消请求  abort()  取消当钱响应  ,关闭连接并且结束任何未解决的网络活动
    47                 xhr.abort()
    48             },timeOut)
    49         }
    50     }
    51     /**
    52      * {name:"张三",
    53       * age:18,
    54       *  }
    55      *  ['name="张三"',"age=18"]
    56      * name="张三" &age =18
    57      * */
    58     /**
    59      * 把对象转换成拼接字符串
    60      * @param {object} paramObj
    61      *
    62      * **/
    63     //设置请求时间
    64 
    65 
    66     function getStrWithObject( paramObj){
    67         var resArr =[];
    68         //1.转化对象
    69         for(var key in paramObj){
    70             var str =key + '='+ paramObj[key];
    71             resArr.push(str)
    72         }
    73         //2.拼接时间戳
    74         resArr.push('random='+ getRandomStr())
    75         //3.数组转成字符串
    76         return resArr.join('&')
    77     }
    78     /**
    79      * 获取时间戳
    80      * */
    81     function getRandomStr(){
    82         return Math.random(new Date().getTime())
    83     }
    84     window.AjaxTool=AjaxTool
    85 })(window)
     1 <!doctype html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <meta name="viewport"
     6           content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
     7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     8     <title>数据请求</title>
     9     <style>
    10         body{
    11           background-color: #00B7FF;
    12         }
    13     </style>
    14 </head>
    15 <body>
    16 <lable>
    17     <input type="text" id="user">
    18 </lable>
    19 <label >
    20     <input type="text" id="pwd">
    21 </label>
    22 <button id="send">发送get请求</button>
    23 <script src="/javascripts/AjaxTest2.js"></script>
    24 <script>
    25     window.addEventListener('load',function () {
    26 
    27 
    28         $("send").addEventListener("click",function () {
    29             var user= $("user").value
    30             var age =$("pwd").value
    31            // AjaxTool.ajaxRequest('') //请求的方式,参数 ,请求的路径 ,回调函数
    32           /*  //01.请求方式
    33             var xhr=new XMLHttpRequest()
    34             //02.请求方法
    35             xhr.open("get","http://localhost:3000/api/Test03?user="+user+"&pwd="+pwd+"&random="+getRandom(),true)
    36             //03.发送请求
    37             xhr.send()
    38             //指定请求回避方式
    39             xhr.addEventListener("readystatechange", function () {
    40                 if(xhr.readyState===4 && xhr.status==200){
    41                     console.log(xhr.responseText)
    42                 }
    43             })*/
    44 
    45           //2.处理参数对象
    46             var paramsObj={
    47                 "name":user,
    48                 "age":age
    49             }
    50             var param={
    51                 "requestType":"get", //请求方式
    52                 "url":"http://localhost:3000/api/Test03",//请求路径
    53                 "timeOut":2000,//请求时长
    54                 "paramObj":paramsObj ,// 请求参数
    55                 "timeOut":2000
    56             }
    57             AjaxTool.ajaxRequest(param,function (xhr) {
    58                 console.log("请求成功")
    59             },function (xhr) {
    60                 console.log("请求失败")
    61             })
    62             // AjaxTool.ajaxRequest('http://localhost:3000/api/Test03',paramsObj,
    63             //      //处理成功的函数
    64             //     function (xhr) {
    65             //     console.log("请求成功")
    66             // },function (xhr) {
    67             //     console.log("请求失败")
    68             // })
    69 
    70         })
    71         function $(id) {
    72             return typeof id==="string"?document.getElementById(id):null
    73         }
    74     })
    75 
    76 </script>
    77 
    78 </body>
    79 </html>
  • 相关阅读:
    tp5.1 多级控制器
    JS中三个点(...)是什么鬼?
    vue reqwest与fetch的使用
    new Vue({ render: h => h(App), }).$mount('#app')到底什么意思
    ant design vue 表格和国际化的使用
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
  • 原文地址:https://www.cnblogs.com/yuanxiangguang/p/11383272.html
Copyright © 2020-2023  润新知