ajax是现在网页开发经常用到的,在jQuery中有$.ajax()函数可以进行异步请求,但是当我要指定返回blob类型的二进制数据对象的时候,jq不支持该类型的数据。但是原生js是支持的,于是对原生的ajax操作做了个封装,使得可以请求blob类型的数据。

/\*\*

 \*

 \* @param 传入的是一个json对象

 \* {

 \*     method:请求方式,

 \*     url:请求地址,

 \*     responseType:返回的数据类型,

 \*     data:请求参数,

 \*     success:请求成功回调

 \*     error:请求失败回调

 \* }

 \* @returns XMLHttpRequest对象

 \*/

function ajax(param) {

   var xhr = null;

   try {

      xhr = new XMLHttpRequest();

   } catch (e) {

      xhr = new ActiveXObject('Microsoft.XMLHTTP');

   }

   if(param.responseType){

        xhr.responseType = param.responseType;

   }else{

        xhr.responseType = "text";

   }

   if (param.method == 'get' && param.data) {

        param.url += '?' + param.data;

   }

   

   xhr.open(param.method,param.url,true);

   if (param.method == 'get') {

      xhr.send();

   } else {

      xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');

      xhr.send(param.data);

   }

   

   xhr.onreadystatechange = function() {

      

      if ( xhr.readyState == 4 ) {

         if ( xhr.status == 200 ) {

                param.success && param.success(xhr.response);

         } else {

                param.error && param.error(xhr.status);

         }

      }

   };

   return xhr;

}