要监控th:each中的按键,并将对应的数据通过ajax传给后端,你可以使用以下步骤:

  1. 给每个按键元素添加一个监听器,用于捕获按键事件。
document.querySelectorAll('.your-button-class').forEach(function(button) {
  button.addEventListener('click', function(event) {
    // 处理按键事件
    var key = event.target.getAttribute('data-key'); // 获取按键对应的数据
    sendDataToBackend(key); // 将数据通过ajax传给后端
  });
});
  1. 编写一个函数sendDataToBackend,用于发送数据到后端。你可以使用XMLHttpRequest对象或者fetch函数来执行ajax请求。

使用XMLHttpRequest的示例:

function sendDataToBackend(key) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/your-backend-url', true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      // 请求成功处理
      console.log(xhr.responseText);
    }
  };
  xhr.send(JSON.stringify({key: key}));
}

使用fetch的示例:

function sendDataToBackend(key) {
  fetch('/your-backend-url', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({key: key})
  })
  .then(function(response) {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Network response was not ok');
  })
  .then(function(data) {
    // 请求成功处理
    console.log(data);
  })
  .catch(function(error) {
    // 请求失败处理
    console.error(error);
  });
}

注意替换上述代码中的your-button-class为你按键元素的类名,/your-backend-url为你的后端接口URL。另外,你可以根据实际需要调整代码逻辑和处理方式。


原文地址: https://www.cveoy.top/t/topic/pLiV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录