• 原生js封装ajax代码


     方法一:(类似jQuery的封装方法)

    1、ajax函数封装:

     1  /*
     2   *author: Ivan
     3   *date: 2014.06.01
     4   *参数说明:
     5   *opts: {'可选参数'}
     6   **method: 请求方式:GET/POST,默认值:'GET';
     7   **url:    发送请求的地址, 默认值: 当前页地址;
     8   **data: string,json;
     9   **async: 是否异步:true/false,默认值:true;
    10   **cache: 是否缓存:true/false,默认值:true;
    11   **contentType: HTTP头信息,默认值:'application/x-www-form-urlencoded';
    12   **success: 请求成功后的回调函数;
    13   **error: 请求失败后的回调函数;
    14 */
    15 function ajax(opts){ 16 //一.设置默认参数 17 var defaults = { 18 method: 'GET', 19 url: '', 20 data: '', 21 async: true, 22 cache: true, 23 contentType: 'application/x-www-form-urlencoded', 24 success: function (){}, 25 error: function (){} 26 }; 27 28 //二.用户参数覆盖默认参数 29 for(var key in opts){ 30 defaults[key] = opts[key]; 31 } 32 33 //三.对数据进行处理 34 if(typeof defaults.data === 'object'){ //处理 data 35 var str = ''; 36 var value = ''; 37 for(var key in defaults.data){ 38 value = defaults.data[key]; 39 if( defaults.data[key].indexOf('&') !== -1 ) value = defaults.data[key].replace(/&/g, escape('&')); //对参数中有&进行兼容处理 40 if( key.indexOf('&') !== -1 ) key = key.replace(/&/g, escape('&')); //对参数中有&进行兼容处理 41 str += key + '=' + value + '&'; 42 } 43 defaults.data = str.substring(0, str.length - 1); 44 } 45 46 defaults.method = defaults.method.toUpperCase(); //处理 method 47 48 defaults.cache = defaults.cache ? '' : '&' + new Date().getTime() ;//处理 cache 49 50 if(defaults.method === 'GET' && (defaults.data || defaults.cache)) defaults.url += '?' + defaults.data + defaults.cache; //处理 url 51 52 //四.开始编写ajax 53 //1.创建ajax对象 54 var oXhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); 55 //2.和服务器建立联系,告诉服务器你要取什么文件 56 oXhr.open(defaults.method, defaults.url, defaults.async); 57 //3.发送请求 58 if(defaults.method === 'GET') 59 oXhr.send(null); 60 else{ 61 oXhr.setRequestHeader("Content-type", defaults.contentType); 62 oXhr.send(defaults.data); 63 } 64 //4.等待服务器回应 65 oXhr.onreadystatechange = function (){ 66 if(oXhr.readyState === 4){ 67 if(oXhr.status === 200) 68 defaults.success.call(oXhr, oXhr.responseText); 69 else{ 70 defaults.error(); 71 } 72 } 73 }; 74 }

    2、ajax函数调用:

     1 //调用ajax函数
     2 
     3 ajax({
     4  
     5    url: '1.php',
     6  
     7    data: {name: 'ivan', sex: 'male', age: '23'},
     8  
     9    success: function (data){ alert('返回数据是:' + data); }
    10  
    11  });
    12  
    13  ajax({
    14  
    15    url: '1.php',
    16  
    17    data: 'name=ivan&sex=male&age=23',
    18  
    19    cache: false,
    20  
    21    success: function (data){ alert('返回数据是:' + data); }
    22  
    23  });

     转摘于:http://www.cnblogs.com/Ivangel/p/3825701.html?utm_source=tuicool&utm_medium=referral  感谢原作者

    方法二:

    1、ajax封装

     1 //ajax封装
     2 function Ajax(type, url, data, success, failed){
     3     // 创建ajax对象
     4     var xhr = null;
     5     if(window.XMLHttpRequest){
     6         xhr = new XMLHttpRequest();
     7     } else {
     8         xhr = new ActiveXObject('Microsoft.XMLHTTP')
     9     }
    10  
    11     var type = type.toUpperCase();
    12     // 用于清除缓存
    13     var random = Math.random();
    14  
    15     if(typeof data == 'object'){
    16         var str = '';
    17         for(var key in data){
    18             str += key+'='+data[key]+'&';
    19         }
    20         //method=get&url=
    21         data = str.replace(/&$/, '');
    22     }
    23  
    24     if(type == 'GET'){
    25         if(data){
    26             xhr.open('GET', url + '?' + data, true);
    27         } else {
    28             xhr.open('GET', url + '?t=' + random, true);
    29         }
    30         xhr.send();
    31  
    32     } else if(type == 'POST'){
    33         xhr.open('POST', url, true);
    34         // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
    35         xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    36         xhr.send(data);
    37     }
    38  
    39     // 处理返回数据
    40     xhr.onreadystatechange = function(){
    41         if(xhr.readyState == 4){
    42             if(xhr.status == 200){
    43                 success(xhr.responseText);
    44             } else {
    45                 if(failed){
    46                     failed(xhr.status);
    47                 }
    48             }
    49         }
    50     }
    51 }

    2、ajax调用

    1 //调用
    2 Ajax('get','check.php',sendData,function(data) {}

    3、ajax注册例子如下

      1 //例子
      2 
      3 <!DOCTYPE html>
      4 <html>
      5     <head>
      6         <meta charset="utf-8" />
      7         <title>ajax注册</title>
      8     </head>
      9     <body>
     10         <form method="post" action="http://www.mytest.com/ajax-09.php" onsubmit="return checkform();">
     11     
     12             用户名:<input type="text" name="username" id="username" onfocus="clearTips()" onblur="checkName();" />
     13             <br/><br/>
     14 
     15             密&nbsp;&nbsp;码:<input type="password" name="userpass1" id="userpass1" onblur="checkPassFirst();" onfocus="clearTips();"/>
     16             <br/><br/>
     17 
     18             确认密码:<input type="password" name="userpass2" id="userpass2" onblur="checkPass();" onfocus="clearTips();" />
     19             <br/><br/>
     20 
     21             邮箱:<input type="text" name="useremail" id="useremail" onblur="checkEmail();" onfocus="clearTips();" />
     22             <br/><br/>
     23 
     24             手机:<input type="text" name="usermobile" id="usermobile" onfocus="clearTips();" onblur="checkMobile();"/><input type="button" value="获取手机验证码" id="mobilebtn" style="display:none;"  onclick="getMobileCode();"/>
     25             <br/><br/>
     26 
     27             验证码:<input type="text" name="vcode" id="vcode" onblur="checkCode();" onfocus="clearTips();"/>
     28             <img id="code" src="http://www.mytest.com/ajax/code.php" style="80;height:24px;border:0;" onclick="changeCode();"/>
     29             <br/><br/>
     30 
     31             <p style="clear:both;500px;color:red;display:none;" id="tips" error=""> </p>
     32             <input type="submit" value="注册" id="submit"/> 
     33       </form>
     34 <script>
     35 function checkform() {
     36     var name = document.getElementById('username').value;
     37     if (name.length <= 0) {
     38         showTips('用户名不能为空');
     39         return false;
     40     }
     41 
     42     var pass = document.getElementById('userpass1').value;
     43     if (pass.length <= 0) {
     44         showTips('密码不能为空');
     45         return false;
     46     }
     47 
     48     var pass2 = document.getElementById('userpass2').value;
     49     if (pass2.length <= 0) {
     50         showTips('确认密码不能为空');
     51         return false;
     52     }
     53 
     54     if (pass != pass2) {
     55         showTips('两次密码输入不一致');
     56         return false;
     57     }
     58 
     59     var email = document.getElementById('useremail').value;
     60     if (email.length <= 0) {
     61         showTips('邮箱不能为空');
     62         return false;
     63     }
     64     var emailReg = /^[w-]+(.[w-]+)*@[w-]+(.[w-]+)+$/; 
     65     if( !emailReg.test(email) ){ 
     66         showTips('邮箱输入有误,请重新输入')
     67         return false; 
     68     } 
     69 
     70     var mobile = document.getElementById('usermobile').value;
     71     if (mobile.length <= 0) {
     72         showTips('手机号不能为空');
     73         return false;
     74     }
     75 
     76     var regu =/^[1][3|4|5|8][0-9]{9}$/gi; 
     77     var re = new RegExp(regu); 
     78     if (!re.test(mobile)) { 
     79         showTips('手机号输入有误,请重新输入')
     80         return false; 
     81     } 
     82 
     83     var code = document.getElementById('vcode').value;
     84     if (code.length <= 0) {
     85         showTips('验证码不能为空');     
     86         return false;
     87     }
     88 
     89     return true;
     90 }
     91 
     92 function clearTips(){
     93     document.getElementById('tips').style.display = "none";
     94     document.getElementById('tips').innerHTML = '';
     95     document.getElementById('submit').disabled = false;
     96 }
     97 
     98 function showTips(msg){
     99     tipObj = document.getElementById('tips');
    100     tipObj.style.display = "block";
    101     tipObj.innerHTML = msg;
    102     document.getElementById('submit').disabled = true;
    103 }
    104 
    105 function loading(){
    106     tipObj = document.getElementById('tips');
    107     tipObj.style.display = "block";
    108     tipObj.innerHTML = '加载中...';
    109 }
    110 
    111 function removeLoading(){
    112     tipObj = document.getElementById('tips');
    113     tipObj.innerHTML = '';
    114     tipObj.style.display = "none";
    115 }
    116 
    117 function checkName(){
    118     var name = document.getElementById('username').value;
    119     if(isNull(name)) {
    120         showTips('请输入用户名');    
    121     }
    122     loading();
    123     var sendData = {username:name,action:'checkname'};
    124     Ajax('get','check.php',sendData,function(data) {
    125         removeLoading(); 
    126         var user = eval('('+data+')')
    127         if (user.id) {
    128             showTips('用户名已被占用,请重新输入用户名');    
    129         }
    130         }, function(data){
    131             
    132             showTips('ajax请求错误');    
    133         });
    134 
    135 }
    136 
    137 function checkEmail(strEmail) { 
    138     var strEmail = document.getElementById('useremail');
    139     var emailReg = /^[w-]+(.[w-]+)*@[w-]+(.[w-]+)+$/; 
    140     if( !emailReg.test(strEmail.value) ){ 
    141         showTips('邮箱输入有误,请重新输入')
    142         return false; 
    143     } 
    144 } 
    145 
    146 function changeCode(){
    147    var url = document.getElementById('code').src ;
    148    var rand = Math.floor(Math.random() * ( 1000 + 1));
    149    url += '?' +  rand;
    150    document.getElementById('code').src  = url;
    151 }
    152  
    153 function checkMobile(s){   
    154     var obj = document.getElementById('usermobile');
    155     var regu =/^[1][3|4|5|8][0-9]{9}$/gi; 
    156     var re = new RegExp(regu); 
    157     if (!re.test(obj.value)) { 
    158         showTips('手机号输入有误,请重新输入')
    159 
    160         var obj = document.getElementById('mobilebtn');
    161         obj.style.display = 'none';
    162         obj.disabled = true;
    163         return false; 
    164     } 
    165     var obj = document.getElementById('mobilebtn');
    166     obj.style.display = 'block';
    167     obj.disabled = false;
    168 } 
    169 
    170 function getMobileCode(){
    171     var obj = document.getElementById('usermobile');
    172     var regu =/^[1][3|4|5|8][0-9]{9}$/gi; 
    173     var re = new RegExp(regu); 
    174     if (!re.test(obj.value)) { 
    175         showTips("手机号输入有误,请重新输入")
    176         return false; 
    177     } 
    178     sendData = {mobile:obj.value, action:"getcode"}
    //ajax调用
    179 Ajax("get","check.php",sendData, function(data){ 180 tipObj = document.getElementById('tips'); 181 tipObj.style.display = "block"; 182 tipObj.innerHTML = "手机验证码是:" + data; 183 }, function(data){ 184 showTips('手机验证码获取错误') ; 185 }); 186 } 187 188 function checkPassFirst(){ 189 var pass = document.getElementById('userpass1').value; 190 if (pass.length <= 0) { 191 showTips('请输入密码'); 192 return false; 193 } 194 195 } 196 197 function checkPass(){ 198 var obj1 = document.getElementById('userpass1'); 199 var obj2 = document.getElementById('userpass2'); 200 if (obj2.value.length <= 0) { 201 showTips('请输入确认密码'); 202 return false; 203 } 204 if (obj1.value != obj2.value ) { 205 showTips('密码与确认密码不对,请重新输入密码'); 206 return false; 207 } 208 } 209 210 function checkCode(){ 211 var obj1 = document.getElementById('vcode'); 212 if (obj1.value.length <= 0) { 213 showTips('请输入验证码'); 214 return false; 215 } 216 if (obj1.value.length != 4) { 217 showTips('请输入正确的验证码'); 218 return false; 219 } 220 } 221 222 function isNull( str ){ 223 if ( str == "" ) return true; 224 var regu = "^[ ]+$"; 225 var re = new RegExp(regu); 226 return re.test(str); 227 } 228 229 230 function addCookie(objName,objValue,objHours){//添加cookie 231 var str = objName + "=" + escape(objValue); 232 if(objHours > 0){//为0时不设定过期时间,浏览器关闭时cookie自动消失 233 var date = new Date(); 234 var ms = objHours*3600*1000; 235 date.setTime(date.getTime() + ms); 236 str += "; expires=" + date.toGMTString(); 237 } 238 document.cookie = str; 239 alert("添加cookie成功"); 240 } 241 242 function getCookie(objName){//获取指定名称的cookie的值 243 var arrStr = document.cookie.split("; "); 244 for(var i = 0;i < arrStr.length;i ++){ 245 var temp = arrStr[i].split("="); 246 if(temp[0] == objName) return unescape(temp[1]); 247 } 248 } 249 250 function delCookie(name){//为了删除指定名称的cookie,可以将其过期时间设定为一个过去的时间 251 var date = new Date(); 252 date.setTime(date.getTime() - 10000); 253 document.cookie = name + "=a; expires=" + date.toGMTString(); 254 } 255 256 //ajax封装 257 function Ajax(type, url, data, success, failed){ 258 // 创建ajax对象 259 var xhr = null; 260 if(window.XMLHttpRequest){ 261 xhr = new XMLHttpRequest(); 262 } else { 263 xhr = new ActiveXObject('Microsoft.XMLHTTP') 264 } 265 266 var type = type.toUpperCase(); 267 // 用于清除缓存 268 var random = Math.random(); 269 270 if(typeof data == 'object'){ 271 var str = ''; 272 for(var key in data){ 273 str += key+'='+data[key]+'&'; 274 } 275 //method=get&url= 276 data = str.replace(/&$/, ''); 277 } 278 279 if(type == 'GET'){ 280 if(data){ 281 xhr.open('GET', url + '?' + data, true); 282 } else { 283 xhr.open('GET', url + '?t=' + random, true); 284 } 285 xhr.send(); 286 287 } else if(type == 'POST'){ 288 xhr.open('POST', url, true); 289 // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。 290 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 291 xhr.send(data); 292 } 293 294 // 处理返回数据 295 xhr.onreadystatechange = function(){ 296 if(xhr.readyState == 4){ 297 if(xhr.status == 200){ 298 success(xhr.responseText); 299 } else { 300 if(failed){ 301 failed(xhr.status); 302 } 303 } 304 } 305 } 306 } 307 </script> 308 </body> 309 </html>
  • 相关阅读:
    C# BackgroundWorker使用总结
    C#如何优雅的结束一个线程
    C#线程中安全访问控件(重用委托,避免繁复的delegate,Invoke)总结
    C#异步方法调用(四大方法详解)
    C# Winform 跨线程更新UI控件常用方法汇总
    走进异步编程的世界
    走进异步编程的世界
    走进异步编程的世界
    Unity-Redis数据存储
    untiy
  • 原文地址:https://www.cnblogs.com/caojiayan/p/6360050.html
Copyright © 2020-2023  润新知