ajax中止、中斷請求的方法

XMLHttpRequest的中止方法

XMLHttpRequest.abort();ios

示例:git

var xhr = new XMLHttpRequest(),
    method = "GET",
    url = "https://developer.mozilla.org/";
xhr.open(method, url, true);

xhr.send();

if (OH_NOES_WE_NEED_TO_CANCEL_RIGHT_NOW_OR_ELSE) {
  xhr.abort();
}

參考:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/abortgithub

axios的中止方法

CancelToken.sourceaxios

示例:post

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

參考:https://github.com/axios/axios#cancellationurl

相關文章
相關標籤/搜索