Ajax

2019-03-09  本文已影响0人  啃香菜的花萝萝

Ajax请求是客户端向服务器发送的一种异步请求。优点就是可以与服务器交换数据并且更新局部网页的内容。

xmlHttpRequest对象

<script>
(function() {
  // 创建XMLHttpRequest 对象
  var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://reqres.in/api/users?page=2');
    // 注册回调
    xhr.onload = function() {
      console.log('request status: ', xhr.status);
      console.log('response data: ', xhr.responseText);
    }
    xhr.send();
 })();
</script>
效果: ajax的get请求
<script>
  (function() {
    var xhr = XMLHttpRequest();
    xhr.open('POST', 'https://reqres.in/api/register');
    // 设置发送数据的格式为json类型
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = function() {
      if(200<= xhr.status <=299) {
        console.log('result: ', JSON.parse(xhr.responseText));
        // 显示到页面中
        var h = document.createElement('h1');
        h.innerHtml = JSON.parse(xhr.responseText).token;
        document.body.appendChild(h);
      }
    }
    xhr.send(JSON.stringify({
      email: 'sun@123.com',
      password: '112233'
    }));
  }) ()
</script>
效果: ajax的post请求

Fetch

Fetch API提供了一个JS接口,用于操作HTTP请求及响应,异步获取资源。
下面2个的返回类型都是 Promise
res.json()格式化为json格式
res.text()格式化为普通文本

<script>
  (function() {
    fetch('https://reqres.in/api/users/2')
    .then(res => res.json())
    .then(res => console.log(res));
  }) ();
</script>
效果: fetch请求数据

Promise

resolvereject是Promise的两个内置函数。
其中resolve事件用then等待;reject事件用catch等待。

function orderFood() {
  return new Promise((resolve, reject) => {
    if (Math.random() > 0.5) {
      resolve('订单正在派送');
    } else {
      reject('菜炒糊了,再等等哟。');
    }
  })

orderFood().then(res => {
  console.log(res);
}).catch(res => {
  console.log(res);
})

console.log('print after above finish');
}

效果:

Promise例子
可以看到的是 print after above finish 这句话先打印,这是因为异步的关系。
上一篇 下一篇

猜你喜欢

热点阅读