美文网首页
九、请求:XHR、Fetch、AJAX

九、请求:XHR、Fetch、AJAX

作者: 懒羊羊3号 | 来源:发表于2019-01-08 12:17 被阅读0次

XMLHttpRequest

var xhr;
if (window.XMLHttpRequest) {  // Mozilla, Safari...
   xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
   try {
     xhr = new ActiveXObject('Msxml2.XMLHTTP');
   } catch (e) {
     try {
       xhr = new ActiveXObject('Microsoft.XMLHTTP');
     } catch (e) {}
   }
}
if (xhr) {
   xhr.onreadystatechange = onReadyStateChange;
   xhr.open('POST', '/api', true);
   // 设置 Content-Type 为 application/x-www-form-urlencoded
   // 以表单的形式传递数据
   xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   xhr.send('username=admin&password=root');
}

// onreadystatechange 方法
function onReadyStateChange() {
   // 该函数会被调用四次
   console.log(xhr.readyState);
   if (xhr.readyState === 4) {
      // everything is good, the response is received
      if (xhr.status === 200) {
         console.log(xhr.responseText);
      } else {
         console.log('There was a problem with the request.');
      }
   } else {
      // still not ready
      console.log('still not ready...');
   }
}

AJAX

$.ajax({
    method: 'POST',
    url: '/api',
    data: { username: 'admin', password: 'root' }
})
  .done(function(msg) {
      alert( 'Data Saved: ' + msg );
  });

Fetch

注意:由于Fetch API是基于Promise设计,旧浏览器不支持Promise,需要使用pollyfill es6-promise

fetch(url, options).then(function(response) { 
// handle HTTP response
}, function(error) {
 // handle network error
})

相关文章

网友评论

      本文标题:九、请求:XHR、Fetch、AJAX

      本文链接:https://www.haomeiwen.com/subject/rfkvrqtx.html