baozhengrui

导航

点击识别按钮调用后端接口,中途按下结束识别,但是识别还是进行啦js

在JavaScript中,如果你想要在点击按钮后调用一个接口,并且在这个过程中按下一个按钮来中断或取消这个请求,你可以使用fetch API来发起请求,并使用AbortController来取消这个请求。以下是一个简单的例子:

// 获取按钮元素
const startButton = document.getElementById('startButton');
const cancelButton = document.getElementById('cancelButton');
 
// 当startButton被点击时,调用startRecognition函数
startButton.addEventListener('click', startRecognition);
 
// 存储fetch请求的signal,以便能够在需要时取消它
let abortController = null;
 
function startRecognition() {
  // 移除按钮点击事件监听器,防止重复触发
  startButton.removeEventListener('click', startRecognition);
  
  // 创建一个新的AbortController
  abortController = new AbortController();
 
  // 发起接口请求
  fetch('your-backend-api-url', {
    signal: abortController.signal,
    method: 'POST', // 根据需要使用POST或GET等
    // 其他配置...
  })
  .then(response => {
    // 处理响应
  })
  .catch(error => {
    if (error.name !== 'AbortError') {
      // 如果错误不是由于取消请求而发生的,则处理错误
    }
  });
 
  // 当cancelButton被点击时,取消请求
  cancelButton.addEventListener('click', () => {
    abortController.abort(); // 中断请求
  });
}

在这个例子中,当用户点击startButton后,startRecognition函数会被触发,并开始调用后端接口。同时,移除startButton的点击事件监听器,防止在请求期间重复触发。当用户点击cancelButton时,会调用abortController.abort()方法,这会抛出一个AbortError异常,中断当前的fetch请求。这样就可以在不完成请求的情况下终止请求过程。

posted on 2024-08-15 14:29  芮艺  阅读(66)  评论(0)    收藏  举报