您好我正在使用此代码。我有一个问题。当我在输入框中输入输入时,它很好。但是当我按下回车键时,页面会刷新一秒钟,输入框会自动清除。
<script>
function book_suggestion() {
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
答案 0 :(得分:1)
您的网页重新加载的原因是因为<form>
元素捕获输入按下。
按输入按将提交表格。
提交没有action=""
属性的表单将提交到同一页面。
提交到不处理请求的页面只会重新加载页面,表单输入将重置为空白。
要解决此问题,请使用javascript禁用“提交输入”以捕获等于13
的按键并返回false或取消该事件。
<input type=text id=book onKeyUp="book_suggestion( event )">
... [snip] ...
function book_suggestion( e ){
if( e.which == 13 ){
e.preventDefault();
e.stopPropagation();
return false;
}
... [snip your code] ...
这应该可以解决问题。
对于它的价值,Stack Overflow上的人通常不会根据您的要求修改您的代码。这是一个简单的修复,可以通过谷歌搜索找到关键字(“catch buttonpress”,“取消事件”等)。
答案 1 :(得分:0)
如果我理解你,你想提交自己的表格数据。您应该在false
函数内返回book_suggestion()
。并将onsubmit
添加到<form>
元素。确保它应该返回。像那样:
<form onsubmit="return book_suggestion();">