var ajax = function(obj) {
  function json2urlstr(json) {
    var arr = [];
    for (var key in json) {
      arr.push(key + '=' + json[key]);
    }
    return arr.join('&');
  }
  if (!obj) throw new Error('parameter error!');
  if (!obj.url) throw new Error('request url not config!');
  if (!obj.data) throw new Error('request data not config!');

  var timer = null;

  obj.type = obj.type || 'GET';
  obj.errorTime = obj.errorTime || 15000;
  obj.timeout = obj.timeout || function() {};
  obj.success = obj.success || function() {};
  obj.error = obj.error || function() {};

  var xhr = null;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveXObject('Msxml2.XMLHTTP');
  }
  if (obj.url.indexOf('json') > -1) {
    var param = json2urlstr(obj.data);
    if (param.length) {
      obj.url += (obj.url.indexOf('?') > -1 ? '&' : '?') + param;
    }
    xhr.open('GET', decodeURIComponent(obj.url), true);
    xhr.send();
  } else {
    if (obj.type == 'POST') {
      if (obj.throughPhp) {
        var param = json2urlstr(obj.data);
        xhr.open('POST', '/swatapps/ape/interface/bridge-post.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
        xhr.send('url=' + obj.url + '&postdata=' + encodeURIComponent(param));
      } else {
        xhr.open('POST', obj.url, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
        xhr.send(json2urlstr(obj.data));
      }
    } else {
      var param = json2urlstr(obj.data);
      if (param.length) {
        obj.url += (obj.url.indexOf('?') > -1 ? '&' : '?') + param;
      }
      if (obj.throughPhp) {
        xhr.open('GET', '/swatapps/ape/interface/bridge.php?url=' + encodeURIComponent(obj.url), true);
      } else {
        xhr.open('GET', decodeURIComponent(obj.url), true);
      }
      xhr.send();
    }
  }
  timer = setTimeout(function() {
    xhr.onreadystatechange = null;
    obj.timeout({
      result: false,
      errorMsg: '网络异常!'
    });
    xhr = null;
    clearTimeout(timer);
  }, obj.errorTime);
  xhr.onreadystatechange = function() {
    // log('xhr.readyState:' + xhr + " " + xhr.readyState + " " + xhr.status + " " + xhr.responseText);
    if (xhr.readyState == 4) {
      clearTimeout(timer);
      // log('xhr.status:' + xhr.status);
      if ((xhr.status < 300 && xhr.status >= 200) || xhr.status == 304) {
        obj.success(xhr.responseText);
        xhr = null;
      } else {
        xhr.onreadystatechange = null;
        obj.error({
          result: false,
          errorMsg: '网络异常!'
        });
        xhr = null;
      }
    }
  };
};
