首页 > Web开发 > 详细

Ajax请求GET方法的封装

时间:2017-05-23 09:56:49      阅读:359      评论:0      收藏:0      [点我收藏+]

function get(url, options, callback){                                        //定义get函数

  if(XMLHttpRequest){

    var xhr=new XMLHttpRequest();

  }else{

    var xhr=new ActiveXObject("Microsoft.XMLHTTP"); //兼容ie

  }


  xhr .onreadystatechange = function(callback) {

    if(xhr .readyState === 4){

      if((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304){

        callback(xhr.responseText);

      }else{

        alert("请求未成功:" + xhr .status )

      }

    }

  }

  var seriUrl = url + ‘?‘ + serialize(options);

  xhr .open(‘get‘,seriUrl, true);

  xhr .send(null);
}


function serialize(data){

  if(!data) return ‘‘;

  var pairs = [], value;

  for(name in data){                                                       //遍历对象属性

    if(!data.hasOwnProperty(name)) continue;        //过滤掉继承原型的属性和方法

    if(typeof data[name] === ‘function‘) continue; //过滤掉函数方法

    value = data[name].toString();                             //属性值转为字符串

    name = encodeURIComponent(name);              //可把属性名称字符串作为URI 组件进行编码。返回值URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。

    value = encodeURIComponent(value);              //属性值进行URI编码。

    pairs.push(name + ‘=‘ + value);                          //属性名和值放入数组

  }

  return pairs.join(‘&‘);                                                 //将数组中的元素用&分隔开返回成字符串形式

}


get(‘/information‘, {name: ‘netease‘, age: 18}, function (data) {

  console.log(data);

  // 处理返回数据

});

Ajax请求GET方法的封装

原文:http://www.cnblogs.com/zhweb/p/6892582.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!