Wednesday, 2 July 2008

My AJAX framework v1.0

Nothing special. Create a new object wjAjax inside there is a XMLHttpRequest object named xmlhttp. And then you can call the function getData (method, url, params, async, func) which attached in wjAjax class. If you call the getData function by asynchronized way, the function will return true or false. But if you call the getData function by synchronized way it will directly return the XMLHttpRequest object for further using.

function wjAjax ()
{
  try
  {
    if (window.XMLHttpRequest)
    {
      this.xmlhttp = new window.XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
      this.xmlhttp = new window.ActiveXObject("MSXML2.XMLHTTP.3.0");
      if (!this.xmlhttp)
        this.xmlhttp = new new window.ActiveXObject("MICROSOFT.XMLHTTP");
    }
  }
  catch (e) {return null;}
  this.isRunning = false;
  return this;
}

wjAjax.prototype.getData = getData;

function getData(method, url, params, async, func)
{
  if (this.isRunning) {return false;}
  if (!url) {return false;}
  if (async && !func) {return false;}
  var me = this; //alias of wjAjax object, for reference using in onreadystatechange method.
  method = method || "get";
  params = params || "";
  try
  {
    if (method.toLowerCase() == "get")
    {
      this.xmlhttp.open("get", url+"?"+params, async);
      params = null;
    }
    else if (method.toLowerCase() == "post")
    {
      this.xmlhttp.open("post", url, async);
      this.xmlhttp.setRequestHeader("Method", "POST "+url+" HTTP/1.1");
      this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }
    if (async)
    {
      this.xmlhttp.onreadystatechange = function()
      {
        if (this.readyState == 4)
        {
          me.isRunning = false;
          if (this.status == 200) {func(this);}
          else {alert ("HTTP server error. The HTTP server response status code is " + this.status);}
        }
      }
    }
    this.isRunning = true;
    this.xmlhttp.send(params);
    if (!async)
      this.isRunning = false;
  }
  catch (e) {alert("Run time error: "+e.message); return false;}
  if (async)
    return true;
  else
    return this.xmlhttp;
}

No comments: