如何用AJAX表单提交回车?

当用户按下按钮时,一切正常;但是当他们按下Enter键时,页面就会重新加载。哪里出错了?

这是我的完整代码:
<!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>

谢谢!

You are setting the onclick event for the button, this will not work when Enter is pressed, because it is not a click.

Take off onclick and add

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

to the <form>.

event.preventDefault(); prevents the submission of the form (the Default action).

return false; is for older versions of Internet Explorer, because they don't support e.preventDefault();. Modern browsers ignore return false;.

When a user presses enter, the form will be submitted. You'll have to look for the onsubmit event of the form, rather than using the onclick event of the button.

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

Now you also have to prevent that the page actually submits (because you did it with AJAX). Add return false; at the end of the function get().

It is better practice to assign the event using jQuery (since you are using it anyway), with the on() method.