原生JS封装ajaxpostget请求方法

Posted echophp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原生JS封装ajaxpostget请求方法相关的知识,希望对你有一定的参考价值。

js_ajax使用说明

本demo是使用原生JS封装的ajax、post、get三种请求方式,以下是使用说明

  • demo中的对象是:ajaxRequest;通过此对象调用ajax、get、post方法


  • 参数:


 
   
   
 
  1. method:               //请求的方式:post 或 get【默认】--ajax方法必传此参数

  2. data:                 //请求的数据信息,对象形式,

  3. success:function(){}  //请求成功时的回调函数

  4. error:function(){}    //请求失败的回调函数

  • 方法:ajax()

 
   
   
 
  1. //例:

  2. ajaxRequest.ajax({

  3.    method:'get',

  4.    url:'php/test.php',

  5.    data:{

  6.        "username":"chen",

  7.        "password":"123456"

  8.    },

  9.    success:function(data){

  10.        console.log(data);

  11.    },

  12.    error:function(error){

  13.        console.log(error);

  14.    }

  15. });

  • 方法:get()

 
   
   
 
  1. //例:

  2. ajaxRequest.get({

  3.    url:'php/test.php',

  4.    data:{

  5.        "username":"chen",

  6.        "password":"123456"

  7.    },

  8.    success:function(data){

  9.        console.log(data);

  10.    },

  11.    error:function(error){

  12.        console.log(error);

  13.    }

  14. });

  • 方法:post()

 
   
   
 
  1. //例:

  2. ajaxRequest.post({

  3.    url:'php/test.php',

  4.    data:{

  5.        "username":"chen",

  6.        "password":"123456"

  7.    },

  8.    success:function(data){

  9.        console.log(data);

  10.    },

  11.    error:function(error){

  12.        console.log(error);

  13.    }

  14. });

demo参考网址

  • JS学习笔记图

  • 源代码

 
   
   
 
  1. var AjaxRequest = function(){

  2.    var that = this;

  3.    //创建XMLHTTPRequest对象

  4.    that.createXHR = function(){

  5.        if (window.XMLHttpRequest){

  6.            // code for IE7+, Firefox, Chrome, Opera, Safari

  7.            return new XMLHttpRequest();

  8.        }else if(window.ActiveXObject){

  9.            // IE6,IE5

  10.            return new ActiveXObject("Microsoft.XMLHTTP");

  11.        }else{

  12.            throw new Error("您的浏览器不支持AJAX!");

  13.        }

  14.    };

  15.    //初始化数据和方法

  16.    that.init = function(obj){

  17.        var objAdapter = {

  18.            method:"get",

  19.            data:{},

  20.            success:function(){},

  21.            complete:function(){},

  22.            error:function(s){

  23.                alert('status:' + s + 'error!');

  24.            },

  25.            async:true

  26.        };

  27.        //通过使用JS随机字符串解决IE浏览器第二次默认获取缓存的问题

  28.        that.url = obj.url + '?rand=' + Math.random();

  29.        that.method = obj.method || objAdapter.method;

  30.        that.data = that.params(obj.data) || that.params(objAdapter.data);

  31.        that.async = obj.async || objAdapter.async;

  32.        that.complete = obj.complete || objAdapter.complete;

  33.        that.success = obj.success || objAdapter.success;

  34.        that.error = obj.error || objAdapter.error;

  35.    };

  36.    //ajax异步调用

  37.    that.ajax = function(obj){

  38.        that.method = obj.method || 'get';

  39.        if(that.method === "post" || that.method === "POST"){

  40.            that.post(obj);

  41.        }else if(that.method === "get" || that.method === "GET"){

  42.            that.get(obj);

  43.        }

  44.    };

  45.    //post方法

  46.    that.post = function(obj){

  47.        var xhr = that.createXHR();//创建XHR对象

  48.        that.init(obj);

  49.        that.method = "post";

  50.        if(that.async===true){

  51.            //异步

  52.            xhr.onreadystatechange = function(){

  53.                //响应已就绪

  54.                if(xhr.readyState==4){

  55.                    that.callback(obj,this); //回调函数

  56.                }

  57.            }

  58.        }

  59.        xhr.open(that.method,that.url,that.async);

  60.        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  61.        xhr.send(that.data);

  62.        if(that.async===false){

  63.            //同步

  64.            that.callback(obj,this);

  65.        }  

  66.    };

  67.    //get方法

  68.    that.get = function(obj){

  69.        var xhr = that.createXHR();//创建XHR对象

  70.        that.init(obj);

  71.        if(that.async===true){

  72.            //异步

  73.            xhr.onreadystatechange = function(){

  74.                //响应已就绪

  75.                if(xhr.readyState==4){

  76.                    that.callback(obj,this); //回调函数

  77.                }

  78.            }

  79.        }

  80.        that.url += that.url.indexOf('?')==-1?'?'+that.data:'&'+that.data;

  81.        xhr.open(that.method,that.url,that.async);

  82.        xhr.send(null);

  83.        if(that.async===false){

  84.            //同步

  85.            that.callback(obj,this);

  86.        }

  87.    };

  88.    //请求成功的回调函数

  89.    that.callback = function(obj,xhr){

  90.        if(xhr.status==200 || xhr.status==304){

  91.            obj.success(xhr.responseText);//回调传递参数

  92.        }else{

  93.            alert('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText);

  94.        }

  95.    };

  96.    //数据转换

  97.    that.params = function(data){

  98.        var arr = [];

  99.        for(var i in data){

  100.            //特殊字符传参产生的问题可以使用encodeURIComponent()进行编码处理

  101.            arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));

  102.        }

  103.        return arr.join('&');

  104.    };

  105.    //返回的结果

  106.    return {

  107.        post:that.post,

  108.        get:that.get,

  109.        ajax:that.ajax

  110.    }

  111. }

  112. var ajaxRequest = new AjaxRequest;

  113. //ajax请求

  114. // ajaxRequest.ajax({

  115. //     method:'get',

  116. //     url:'php/test.php',

  117. //     data:{

  118. //         "username":"chen",

  119. //         "password":"123456"

  120. //     },

  121. //     success:function(data){

  122. //         console.log(data);

  123. //     },

  124. //     error:function(error){

  125. //         console.log(error);

  126. //     }

  127. // });

  128. //get请求

  129. // ajaxRequest.get({

  130. //     url:'php/test.php',

  131. //     data:{

  132. //         "username":"chen",

  133. //         "password":"123456"

  134. //     },

  135. //     success:function(data){

  136. //         console.log(data);

  137. //     },

  138. //     error:function(error){

  139. //         console.log(error);

  140. //     }

  141. // });

  142. //post请求

  143. ajaxRequest.post({

  144.    url:'php/test.php',

  145.    data:{

  146.        "username":"chen",

  147.        "password":"123456"

  148.    },

  149.    success:function(data){

  150.        console.log(data);

  151.    },

  152.    error:function(error){

  153.        console.log(error);

  154.    }

  155. });


以上是关于原生JS封装ajaxpostget请求方法的主要内容,如果未能解决你的问题,请参考以下文章

原生js 封装ajax请求超详细

原生js封装ajax代码

原生的js实现jsonp的跨域封装

原生Js封装ajax方法

原生js封装Ajax的GET请求

回归 | js实用代码片段的封装与总结(持续更新中...)