您现在的位置:首页 >> 前端 >> 内容

实现ajax异步请求笔记

时间:2017/6/27 11:10:00 点击:

  核心提示:var xhr = new (window.XMLHttpRequest || ActiveXObject)(Microsoft.XMLHTTP);xhr.open( options.type, op...
  var xhr = new (window.XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP');
  xhr.open( options.type, options.url + search, options.async );
  xhr.onreadystatechange = function() {
   if( xhr.readyState == 4 ) {
    if( xhr.status >= 200 && xhr.status < 300 || xhr.status == 304 ) {
     var text = xhr.responseText;
     // json格式转换
     if(options.dataType == 'json') {
       text = parseJSON(text)
     }
     if( typeof options.success === 'function') {
      options.success(text,xhr.status)
     }
    }else {
     if(typeof options.fail === 'function') {
      options.fail('获取失败', 500)
     }
    
    }
   }
  }
  xhr.setRequestHeader('content-type',options.contentType);
  // get请求时param时null
  xhr.send(param);


  // 如果设置了超时,就定义
  if(typeof options.timeout === 'number') {
   // ie9+
   if( xhr.timeout ) {
    xhr.timeout = options.timeout;
   }else {
    setTimeout(function() {
     xhr.abort();
    },options.timeout)
   }
  }
 }

Tags:实现 现A AJ JA 
作者:网络 来源:wangning_e