ajax封装

//原生写ajax
function ajax (url, fnsuccess) {
  if (window.XMLHttpRequest) {
    var xhr = new XMLHttpRequest(); // 标准浏览器
  } else {
  var xhr = new ActiveXObject('Microsoft.XMLHTTP') // ie6
  }

 

// 自己设置http协议
  // 请求行
  xhr.open('get', 'url')
  //请求头
  xhr.setRequestHeader('content-type', 'text/html')
  //请求主体
  xhr.send(null)

 

// 无法确定服务器什么时候响应,所以要适用事件监听服务器的相应
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4){ //请求响应完成
      if (xhr.status == 200) {  //且成功
        fnsuccess(xhr.responseText)
    } else {
      if (fnfiled) {
        fnfield(xhr.status)
       }
      }
    }
   }
  }
posted @ 2018-08-29 15:19  cecelingmeng  阅读(75)  评论(0编辑  收藏  举报