无法通过输入密钥获取号码而无需重新加载整个页面

时间:2017-01-18 23:31:03

标签: javascript html

目前我正在开发一个简单的数学游戏,用户点击回车键提交数学问题的答案。但是,当按下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
        }
    }
}

2 个答案:

答案 0 :(得分:1)

非常简单的解决方案。您的函数必须为return false。使用该返回值,通常的表单执行将被停止。 如前所述,更好的方法是不使用表单,而只是使用输入本身,如果需要,使用XMLHttpRequest模块执行请求 - &gt; AJAX。

HTML:

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

答案 1 :(得分:0)

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
        }
    }
}
相关问题