繁体   English   中英

无法在不重新加载整个页面的情况下用Enter键提交编号

[英]Having trouble getting number submitted with enter key without reloading entire page

目前,我正在开发一个简单的数学游戏,用户按下Enter键即可提交数学问题的答案。 但是,当按下Enter键时,所有变量都将重置,并且所有内容都将被清除。

我知道这可能是一个常见问题,但对于尚未尝试使用搜索栏的用户,我尚未看到答案。 我只是使用数字输入。 我只是想避免重新加载页面,并在按下Enter键时使用我的功能。 我真的只是想通过回车按钮获得答案,而不刷新我的页面。

用于答案收集的HTML:

<form align= "center" id = "form">
    <input type ="number" id ="answer" value ="" autofocus>
</form>

JavaScript代码:

document.getElementById("answer").onkeydown = function (event){ 
    if(problems != 0){
        if(event.keyCode == 13){
            //some code in here
        }
    }
}

非常简单的解决方案。 您的函数必须return false 使用该返回值,通常的表单执行将停止。 如前所述,一种更好的方法是不使用表单,而仅使用输入本身,并在需要时通过XMLHttpRequest模块-> ajax进行请求。

HTML:

<div align= "center" id = "form">
    <input type ="number" id ="answer" value ="" autofocus>
</div>
document.getElementById("answer").onkeydown = function (event)
{   
    if(problems != 0){
        if(event.keyCode == 13)
        {
            // stop the form from submitting (thus reloading the page)
            e.preventDefault();

            // number to send
            var number = this.value;

            var request = new XMLHttpRequest();
            // don't forget to fill with a valid url to your php file
            request.open("POST", "your url goes here", true);
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.onreadystatechange = function() {
                if(request.readyState == 4 && request.status == 200) {
                    //request.response holds the returned data from the server if you want to is it use it here.
                    // or pass it to another function (also here).
                }
            }
            request.send("yourInputName=" + number);
            // so you can get it using $_POST['yourInputName'] in php
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM