Php 使用Enter提交AJAX表单

Php 使用Enter提交AJAX表单,php,ajax,Php,Ajax,当用户点击按钮时,一切正常。但当他们点击回车键时,页面就会重新加载。我做错了什么 以下是我的完整代码: <!doctype html> <html> <head> <title>Fun!</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <link rel="stylesheet" href

当用户点击按钮时,一切正常。但当他们点击回车键时,页面就会重新加载。我做错了什么

以下是我的完整代码:

<!doctype html>
<html>
<head>
    <title>Fun!</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <link rel="stylesheet" href="" media="print" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

    <style type="text/css">
        body {
            font-family: arial;
        }
    </style>

    <script type="text/javascript">
        function get() {
            $.post('data.php', { name: form.name.value }, 
                function(output) {
                    $('#age').html(output).show();
                }
            );
        }
    </script>
</head>

<body>
    <div class="container">
        <form action="" name="form" method="post">
            <input type="text" name="name" /> <input type="button" value="Get" onClick="get();" />
        </form><br />

        <div id="age" style="display: none;">Result</div>
    </div>
</body>
</html>

有趣!
身体{
字体系列:arial;
}
函数get(){
$.post('data.php',{name:form.name.value},
功能(输出){
$('#age').html(输出).show();
}
);
}

结果

谢谢。

您正在为按钮设置
onclick
事件,当按下Enter键时,这将不起作用,因为它不是单击

取下
onclick
并添加

onsubmit="event.preventDefault();get();return false;"

event.preventDefault()
阻止
s表单的提交(默认操作)


返回false
用于Internet Explorer的旧版本,因为它们不支持
e.preventDefault()。现代浏览器忽略
返回false

当用户按enter键时,表单将被提交。您必须查找表单的
onsubmit
事件,而不是使用按钮的
onclick
事件

<form ... onsubmit="get();">
    ...
</form>

...
现在,您还必须防止页面实际提交(因为您是使用AJAX提交的)。添加
返回false在函数的末尾
get()


更好的做法是使用jQuery(因为您仍然在使用它)和该方法分配事件。

感谢您的帮助,但它仍然只是重新加载页面<代码>
我缺少什么吗?使用
onsubmit=“event.preventDefault();get();”
<代码>默认值()阻止提交表单的默认操作。感谢您的帮助,但它仍然只是重新加载页面

我是否遗漏了什么?@user1453094您必须通过在函数get()中返回false来防止真正的页面刷新(提交)。