在 AJAX 中通过按 Enter 键从输入框获取值,可以通过监听键盘事件来实现。以下是一个简单的示例,展示了如何实现这一功能:
keydown
、keyup
和 keypress
。keydown
事件,当用户按下 Enter 键时,获取输入框的值并通过 AJAX 发送到服务器。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Enter Key Example</title>
</head>
<body>
<input type="text" id="inputField" placeholder="Enter text here">
<div id="result"></div>
<script src="script.js"></script>
</body>
</html>
document.addEventListener('DOMContentLoaded', function() {
const inputField = document.getElementById('inputField');
const resultDiv = document.getElementById('result');
inputField.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault(); // 阻止默认行为(如表单提交)
const inputValue = inputField.value;
sendAjaxRequest(inputValue);
}
});
function sendAjaxRequest(value) {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/your-server-endpoint', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
resultDiv.innerHTML = 'Server response: ' + xhr.responseText;
} else {
resultDiv.innerHTML = 'Error: ' + xhr.statusText;
}
};
xhr.onerror = function() {
resultDiv.innerHTML = 'Network Error';
};
const data = JSON.stringify({ value: value });
xhr.send(data);
}
});
event.preventDefault()
阻止这些默认行为。onerror
事件处理程序以捕获和处理网络错误。通过上述方法,可以有效地在 AJAX 中通过按 Enter 键从输入框获取值,并实现良好的用户体验和实时交互效果。
领取专属 10元无门槛券
手把手带您无忧上云