如何使用纯JavaScript进行AJAX调用?

时间:2015-07-01 07:48:12

标签: javascript ajax

我是Ajax和Javascript的新手,所以我需要使用纯javascript将此示例转换为ajax。如何将此javascript称为ajax及其functional.need方法,如Common.prototype.ajax = function(method,url) ,数据,回调){}; Common.prototype.ajaxGet = function(url,callback){}; Common.prototype.ajaxPost = function(url,data,callback){};

    function Common() {
        console.log("Common Contructor fires!");
    }

    Common.prototype.setEvent = function(evt, element, callback) {
        var obj_idfier = element.charAt(0);
        var elementName = element.split(obj_idfier)[1];
        if (obj_idfier == '#') {
            var _ele = document.getElementById(elementName);
            _ele.addEventListener(evt, callback, false);
        } else if (obj_idfier == '.') {
            var _els = document.getElementsByClassName(elementName);
            for (var i=0; i<_els.length; i++) {
                _els[i].addEventListener(evt, callback, false);
            }
        } else {
            console.log("Undefined element");
            return false;
        }
        return this;
    };

    Common.prototype.getInnerHtml = function(id){
       return document.getElementById(id).innerHTML;
    };

    Common.prototype.setInnerHtml = function(ele, val){
       ele.innerHTML = val;
    };

    Common.prototype.getVal = function(ele){
       return ele.value;
    };

    Common.prototype.setVal = function(ele, val){
       ele.value = val;
    };


 function Calculator() {
console.log("Calculater Constructor");
}


Calculator.prototype = new Common;

Calculator.prototype.init = function() {
  var _this = this;
  var _ele = document.getElementById("math");
  var _numEle = document.getElementById("number");

      this.setEvent("click", ".control", function() { 
          console.log(this.value);
          var _num = _this.getInnerHtml('math');
          _num = _num + "" + _this.getVal(this);
          _this.setInnerHtml(_ele, _num);
      });

      this.setEvent("click", ".input", function() { 
          console.log(this.value);
          var _num = _this.getInnerHtml('math');
          _num = _num + "" + _this.getVal(this);
          _this.setInnerHtml(_ele, _num);
      });

      this.setEvent("click", ".clear", function() { 
          console.log(this.value);
          _this.setInnerHtml(_ele, "");
          _this.setInnerHtml(_numEle, "");
      });

      this.setEvent("click", ".submit", function() { 
          console.log(this.value);
      var _num = _this.getInnerHtml('math');
          _num = eval(_num+""+ _this.getVal(this));
          _this.setInnerHtml(_numEle, _num);
      });       

      };
      var calcObj = new Calculator();
     calcObj.init();

1 个答案:

答案 0 :(得分:0)

您可以为xhr调用构建一般方法:

function xhr (type, url, data, options) {
  options = options || {};
  var request = new XMLHttpRequest();
  request.open(type, url, true);
  if(type === "POST"){
      request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  }
  request.onreadystatechange = function () {
    if (this.readyState === 4) {
      if (this.status >= 200 && this.status < 400) {
        options.success && option.success(parse(this.responseText));
      } else {
        options.error && options.error(this.status);
      }
    }
  };
  request.send(data);
}

function parse(text){
  try {
     return JSON.parse(text);
  } catch(e){
     return text;
  }
}

然后使用它来获取特定的HTTP方法:

Common.prototype.ajax = function(method, url, data, callback) {
    return xhr(method, url, data, {success:callback});
}

Common.prototype.ajaxGet = function(url, callback) {
    return xhr("GET", url, undefined, {success:callback});
}

Common.prototype.ajaxPost = function(url, data, callback) {
    return xhr("POST", url, data, {success:callback});
}