Xmlhttprequest类设计

 

web项目中少不了用ajax,这是很不错的一种技术,但是如果没有把xmlhttprequest这一个对象给好好的包装一下的话,那就对整个项目的影响是很大的。在公司的项目中我用了这样一个类,我认为包装的很好。因为这一个类是开源的,所以可以放到这里来分享一下.

首先要确保此类可以在不同的浏览器下面运行。

关于xmlhttprequest的创建

createXMLHttpRequest : function ()

{

var xhr = null;

        /* 如果是ie浏览器,就执行如下的创建对象的方法,因为iexmlhttprequest

  对象实现的方法是以插件方式来实现的.

 */

    if (window.ActiveXObject)

    {

      var versions = ['Microsoft.XMLHTTP', 'MSXML6.XMLHTTP', 'MSXML5.XMLHTTP', 'MSXML4.XMLHTTP', 'MSXML3.XMLHTTP', 'MSXML2.XMLHTTP', 'MSXML.XMLHTTP'];

 

      for (var i = 0; i < versions.length; i ++ )

      {

        try

        {

          xhr = new ActiveXObject(versions[i]);

          break;

        }

        catch (ex)

        {

          continue;

        }

      }

    }

    else

{

   /* 如果是非ie浏览器,就用如下方法来实现*/

      xhr = new XMLHttpRequest();

    }

 

    return xhr;

}

刚创建了对象是没有任何意义的,人何人之间对想交流,客户端也最想和服务器进行交流,但是交流就得传递参数,但是在传递参数前要对参数进行加工,不要传递一此服务器无法理解的参数

 

parseParams : function (params)

  {

    var legalParams = "";

    params = params ? params : "";

  /* 参数的类型进行确认 */        

if (typeof(params) === "string")

    {

      legalParams = params;  /* string就直接进行传递*/

    }

    else if (typeof(params) === "object")

    {

      try

      {

          /* 我用jquery的插件来把对象转变成json */

        legalParams = "JSON=" + $.toJSON(params); /* 如果是对象类型就转变成json进行传递 */

      }

      catch (ex)

      {

        alert("Can't stringify JSON!");

        return false;

      }

    }

    else

    {

      alert("Invalid parameters!");

      return false;

    }

        return legalParams;

  },

要传递的参数也准备好了,下一步就是把这些参数用前面的对象传递的服务器。

/* *

  * 调用此方法发送HTTP请求。

  *

  * @public

  * @param   {string}    url             请求的URL地址

  * @param   {mix}       params          发送参数

  * @param   {Function}  callback        回调函数

  * @param   {string}    ransferMode     请求的方式,有"GET""POST"两种

  * @param   {string}    responseType    响应类型,有"JSON""XML""TEXT"三种

  * @param   {boolean}   asyn            是否异步请求的方式

  * @param   {boolean}   quiet           是否安静模式请求

  */

run : function (url, params, callback, transferMode, responseType, asyn, quiet)

{

    /*先把参数整理一下 */

params = this.parseParams(params);

/* 用什么方法对数据进行传送,默认的就是GET */

    transferMode = typeof(transferMode) === "string"

    && transferMode.toUpperCase() === "GET"

    ? "GET"

    : "POST";

 

    if (transferMode === "GET")

    {

      var d = new Date();

       /* 把参数加载到url后面 */

      url += params ? (url.indexOf("?") === - 1 ? "?" : "&") + params : "";

      url = encodeURI(url) + (url.indexOf("?") === - 1 ? "?" : "&") + d.getTime() + d.getMilliseconds();

      params = null;

    }

     /* 确定返回类型的数据 */

responseType = typeof(responseType) === "string" && ((responseType = responseType.toUpperCase()) === "JSON" || responseType === "XML") ? responseType : "TEXT";

/* 默认是异步传送 */

    asyn = asyn === false ? false : true;

 

    /* 创建xmlhttprequest对象 */

    var xhr = this.createXMLHttpRequest();

 

    try

    {

      var self = this;

 

      if (typeof(self.onRunning) === "function" && !quiet)

      {

        self.onRunning();

      }

      

      /* 打开连接*/

      xhr.open(transferMode, url, asyn);

      /* 如果是以POST方式来传输 */

      if (transferMode === "POST")

      {

          /* 设置提交类型 */

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

      }

     /* 如果是异步提交 */

      if (asyn)

      {

        xhr.onreadystatechange = function ()

        {

          if (xhr.readyState == 4)

          {

            switch ( xhr.status )

            {

              case 0:

              case 200: // OK!

                /*

                 * If the request was to create a new resource

                 * (such as post an item to the database)

                 * You could instead return a status code of '201 Created'

                 */

 

                if (typeof(self.onComplete) === "function")

                {

                  self.onComplete();

                }

 

                if (typeof(callback) === "function")

                {

                  callback.call(self, self.parseResult(responseType, xhr), xhr.responseText);

                }

              break;

 

              case 304: // Not Modified

                /*

                 * This would be used when your Ajax widget is

                 * checking for updated content,

                 * such as the Twitter interface.

                 */

              break;

 

              case 400: // Bad Request

                /*

                 * A bit like a safety net for requests by your JS interface

                 * that aren't supported on the server.

                 * "Your browser made a request that the server cannot understand"

                 */

                 alert("XmlHttpRequest status: [400] Bad Request");

              break;

 

              case 404: // Not Found

                alert("XmlHttpRequest status: [404] /nThe requested URL "+url+" was not found on this server.");

              break;

 

              case 409: // Conflict

                /*

                 * Perhaps your JavaScript request attempted to

                 * update a Database record

                 * but failed due to a conflict

                 * (eg: a field that must be unique)

                 */

              break;

 

              case 503: // Service Unavailable

                /*

                 * A resource that this request relies upon

                 * is currently unavailable

                 * (eg: a file is locked by another process)

                 */

                 alert("XmlHttpRequest status: [503] Service Unavailable");

              break;

 

              default:

                alert("XmlHttpRequest status: [" + xhr.status + "] Unknow status.");

            }

 

            xhr = null;

          }

        }

        if (xhr != null) xhr.send(params);

      }

      else

      {

        if (typeof(self.onRunning) === "function")

        {

          self.onRunning();

        }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值