// 获取按钮和状态元素 const forwardBtn = document.getElementById('forwardBtn'); const backwardBtn = document.getElementById('backwardBtn'); const status = document.getElementById('status'); // 实际控制函数 function controlMotor(direction) { status.innerHTML = `
正在${direction === 'forward' ? '前进' : '后退'}...
`; // 发送AJAX请求到后端服务器 fetch('/control', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ direction: direction }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { status.innerHTML = `${data.message}
`; } else { status.innerHTML = `错误: ${data.message}
`; } }) .catch(error => { status.innerHTML = `通信错误: ${error.message}
`; }); } // 按钮点击事件 forwardBtn.addEventListener('click', () => { controlMotor('forward'); }); backwardBtn.addEventListener('click', () => { controlMotor('backward'); });