zoukankan      html  css  js  c++  java
  • javascript

      1             /*
      2              * ajax方法
      3              */
      4             var Ajax = function() {
      5                 var that = this;
      6                 //创建异步请求对象方法
      7                 that.createXHR = function() {
      8                     if(window.XMLHttpRequest) { //IE7+、Firefox、Opera、Chrome 和Safari
      9                         return new XMLHttpRequest();
     10                     } else if(window.ActiveXObject) { //IE6 及以下
     11                         var versions = ['MSXML2.XMLHttp', 'Microsoft.XMLHTTP'];
     12                         for(var i = 0, len = versions.length; i < len; i++) {
     13                             try {
     14                                 return new ActiveXObject(version[i]);
     15                                 break;
     16                             } catch(e) {
     17                                 //跳过
     18                             }
     19                         }
     20                     } else {
     21                         throw new Error('浏览器不支持XHR对象!');
     22                     }
     23                 }
     24                 //初始化数据方法
     25                 that.init = function(obj) {
     26                     //初始化数据
     27                     var objAdapter = {
     28                             method: 'get',
     29                             data: {},
     30                             success: function() {},
     31                             complete: function() {},
     32                             error: function(s) {
     33                                 alert('status:' + s + 'error!');
     34                             },
     35                             async: true
     36                         }
     37                         //通过使用JS随机字符串解决IE浏览器第二次默认获取缓存的问题
     38                     that.url = obj.url + '?rand=' + Math.random();
     39                     that.method = obj.method || objAdapter.method;
     40                     that.data = that.params(obj.data) || that.params(objAdapter.data);
     41                     that.async = obj.async || objAdapter.async;
     42                     that.complete = obj.complete || objAdapter.complete;
     43                     that.success = obj.success || objAdapter.success;
     44                     that.error = obj.error || objAdapter.error;
     45                 }
     46                 //ajax异步调用
     47                 that.ajax = function(obj) {
     48                     that.method = obj.method || 'get';
     49                     if(obj.method === 'post'){
     50                         that.post(obj);
     51                     }else{
     52                         that.get(obj);
     53                     }
     54                 }
     55                 //post方法
     56                 that.post = function(obj) {
     57                     var xhr = that.createXHR(); //创建XHR对象
     58                     that.init(obj);
     59                     that.method='post';
     60                     if(that.async === true) { //true表示异步,false表示同步
     61                         //使用异步调用的时候,需要触发readystatechange 事件
     62                         xhr.onreadystatechange = function() {
     63                             if(xhr.readyState == 4) { //判断对象的状态是否交互完成
     64                                 that.callback(obj,this); //回调
     65                             }
     66                         };
     67                     }
     68                     //在使用XHR对象时,必须先调用open()方法,
     69                     //它接受三个参数:请求类型(get、post)、请求的URL和表示是否异步。
     70                     xhr.open(that.method, that.url, that.async);
     71                     //post方式需要自己设置http的请求头,来模仿表单提交。
     72                     //放在open方法之后,send方法之前。
     73                     xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
     74                     xhr.send(that.data); //post方式将数据放在send()方法里
     75                     if(that.async === false) { //同步
     76                         that.callback(obj,this); //回调
     77                     }
     78                 };
     79                 //get方法
     80                 that.get = function(obj) {
     81                     var xhr = that.createXHR(); //创建XHR对象
     82                     that.init(obj);
     83                     if(that.async === true) { //true表示异步,false表示同步
     84                         //使用异步调用的时候,需要触发readystatechange 事件
     85                         xhr.onreadystatechange = function() {
     86                             if(xhr.readyState == 4) { //判断对象的状态是否交互完成
     87                                 that.callback(obj,this); //回调
     88                             }
     89                         };
     90                     }
     91                     //若是GET请求,则将数据加到url后面
     92                     that.url += that.url.indexOf('?') == -1 ? '?' + that.data : '&' + that.data;
     93                     //在使用XHR对象时,必须先调用open()方法,
     94                     //它接受三个参数:请求类型(get、post)、请求的URL和表示是否异步。
     95                     xhr.open(that.method, that.url, that.async);
     96                     xhr.send(null); //get方式则填null
     97                     if(that.async === false) { //同步
     98                         that.callback(obj,this); //回调
     99                     }
    100                 }
    101                 //请求成功后,回调方法
    102                 that.callback = function(obj,xhr) {
    103                         if(xhr.status == 200) { //判断http的交互是否成功,200表示成功
    104                             obj.success(xhr.responseText); //回调传递参数
    105                         } else {
    106                             alert('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText);
    107                         }
    108                     }
    109                 //数据转换
    110                 that.params = function(data) {
    111                     var arr = [];
    112                     for(var i in data) {
    113                         //特殊字符传参产生的问题可以使用encodeURIComponent()进行编码处理
    114                         arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
    115                     }
    116                     return arr.join('&');
    117                 }
    118                 return {
    119                     post : that.post,
    120                     get : that.get,
    121                     ajax : that.ajax
    122                 }
    123             }

    上述的Ajax方法可以看成是一个类,共有方法有:

       1. 初始化数据方法init(),

       2. 创建异步请求对象方法createXHR(),

       3.请求方法ajax(),post(),get(),

       4.请求成功后回调方法callback(),

       5.数据格式转换方法params()

    也可以看成一个函数,return 返回的json对象中定义的接口用于函数内方法的调用 

    故而有有两种方式进行使用封装的Ajax

    函数方式:测试代码数据

     1             Ajax().post({
     2                 url: 'ajax.php',
     3                 data: {
     4                     'name': 'JR',
     5                     'age': 22
     6                 },
     7                 success: function(message) {
     8                     console.log(message);
     9                 },
    10                 async: true
    11             });

    类方式:测试代码数据

     1             var ajax = new Ajax();
     2             ajax.post({
     3                 url: 'ajax.php',
     4                 data: {
     5                     'name': 'JR',
     6                     'age': 22
     7                 },
     8                 success: function(message) {
     9                     console.log(message);
    10                 },
    11                 async: true
    12             });

    对上述封装的ajax方法进行优化

      1var Ajax = {
      2                 //ajax模块
      3                 init: function(obj) {
      4                     //初始化数据
      5                     var objAdapter = {
      6                             url: '',
      7                             method: 'get',
      8                             data: {},
      9                             success: function() {},
     10                             complete: function() {},
     11                             error: function(s) {
     12                                 alert('status:' + s + 'error!');
     13                             },
     14                             async: true
     15                         }
     16                         //通过使用JS随机字符串解决IE浏览器第二次默认获取缓存的问题
     17                     objAdapter.url = obj.url + '?rand=' + Math.random();
     18                     objAdapter.method = obj.method || objAdapter.method;
     19                     objAdapter.data = Ajax.params(obj.data) || Ajax.params(objAdapter.data);
     20                     objAdapter.async = obj.async || objAdapter.async;
     21                     objAdapter.complete = obj.complete || objAdapter.complete;
     22                     objAdapter.success = obj.success || objAdapter.success;
     23                     objAdapter.error = obj.error || objAdapter.error;
     24                     return objAdapter;
     25                 },
     26                 //创建XMLHttpRequest对象
     27                 createXHR: function() {
     28                     if(window.XMLHttpRequest) { //IE7+、Firefox、Opera、Chrome 和Safari
     29                         return new XMLHttpRequest();
     30                     } else if(window.ActiveXObject) { //IE6 及以下
     31                         var versions = ['MSXML2.XMLHttp', 'Microsoft.XMLHTTP'];
     32                         for(var i = 0, len = versions.length; i < len; i++) {
     33                             try {
     34                                 return new ActiveXObject(version[i]);
     35                                 break;
     36                             } catch(e) {
     37                                 //跳过
     38                             }
     39                         }
     40                     } else {
     41                         throw new Error('浏览器不支持XHR对象!');
     42                     }
     43                 },
     44                 params: function(data) {
     45                     var arr = [];
     46                     for(var i in data) {
     47                         //特殊字符传参产生的问题可以使用encodeURIComponent()进行编码处理
     48                         arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
     49                     }
     50                     return arr.join('&');
     51                 },
     52                 callback: function(obj, xhr) {
     53                     if(xhr.status == 200) { //判断http的交互是否成功,200表示成功
     54                         obj.success(xhr.responseText); //回调传递参数
     55                     } else {
     56                         alert('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText);
     57                     }
     58                 },
     59                 ajax: function(obj) {
     60                     if(obj.method === 'post') {
     61                         Ajax.post(obj);
     62                     } else {
     63                         Ajax.get(obj);
     64                     }
     65                 },
     66                 //post方法
     67                 post: function(obj) {
     68                     var xhr = Ajax.createXHR(); //创建XHR对象
     69                     var opt = Ajax.init(obj);
     70                     opt.method = 'post';
     71                     if(opt.async === true) { //true表示异步,false表示同步
     72                         //使用异步调用的时候,需要触发readystatechange 事件
     73                         xhr.onreadystatechange = function() {
     74                             if(xhr.readyState == 4) { //判断对象的状态是否交互完成
     75                                 Ajax.callback(opt, xhr); //回调
     76                             }
     77                         };
     78                     }
     79                     //在使用XHR对象时,必须先调用open()方法,
     80                     //它接受三个参数:请求类型(get、post)、请求的URL和表示是否异步。
     81                     xhr.open(opt.method, opt.url, opt.async);
     82                     //post方式需要自己设置http的请求头,来模仿表单提交。
     83                     //放在open方法之后,send方法之前。
     84                     xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
     85                     xhr.send(opt.data); //post方式将数据放在send()方法里
     86                     if(opt.async === false) { //同步
     87                         Ajax.callback(obj, xhr); //回调
     88                     }
     89                 },
     90                 //get方法
     91                 get: function(obj) {
     92                     var xhr = Ajax.createXHR(); //创建XHR对象
     93                     var opt = Ajax.init(obj);
     94                     if(opt.async === true) { //true表示异步,false表示同步
     95                         //使用异步调用的时候,需要触发readystatechange 事件
     96                         xhr.onreadystatechange = function() {
     97                             if(xhr.readyState == 4) { //判断对象的状态是否交互完成
     98                                 Ajax.callback(obj, xhr); //回调
     99                             }
    100                         };
    101                     }
    102                     //若是GET请求,则将数据加到url后面
    103                     opt.url += opt.url.indexOf('?') == -1 ? '?' + opt.data : '&' + opt.data;
    104                     //在使用XHR对象时,必须先调用open()方法,
    105                     //它接受三个参数:请求类型(get、post)、请求的URL和表示是否异步。
    106                     xhr.open(opt.method, opt.url, opt.async);
    107                     xhr.send(null); //get方式则填null
    108                     if(opt.async === false) { //同步
    109                         Ajax.callback(obj, xhr); //回调
    110                     }
    111                 }
    112             };

    测试代码

     1             Ajax.post({
     2                 url: 'ajax.php',
     3                 data: {
     4                     'name': 'JR',
     5                     'age': 22
     6                 },
     7                 success: function(message) {
     8                     console.log(message);
     9                 },
    10                 async: true
    11             });

    ajax.php页面代码

    1 <?php
    2 echo $_POST['name'];
    3 ?>

    控制台显示

  • 相关阅读:
    HADOOP_HIVE安装和配置
    LInux__增加交换空间(SWAP)的大小
    ORACLE__Linux下Oracle数据库的卸载、删除
    HADOOP__HBASE集群安装(自带ZOOKEEPER)
    HADOOP__PIG安装与配置
    HADOOP__HADOOP基础安装和配置
    PYTHON__Thread达到上限的解决方案(设置线程上限)
    MYSQL__MYSQL的一些基础设置
    Android Studio Unable to access Android SDK addon list Mac
    dmg 文件打不开,双击没反应
  • 原文地址:https://www.cnblogs.com/jtnote/p/6022346.html
Copyright © 2011-2022 走看看