[英]AJAX Form Submit With Enter
When a user hits the button, everything works fine. 当用户点击按钮时,一切正常。 But when they hit enter, the page just reloads.
但当他们点击进入时,页面才会重新加载。 What am I doing wrong?
我究竟做错了什么?
Here's my full code: 这是我的完整代码:
<!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>
Thanks. 谢谢。
You are setting the onclick
event for the button, this will not work when Enter is pressed, because it is not a click. 您正在为按钮设置
onclick
事件,按下Enter键时这将不起作用,因为它不是单击。
Take off onclick
and add 取消
onclick
并添加
onsubmit="event.preventDefault();get();return false;"
to the <form>
. 到
<form>
。
event.preventDefault();
prevent
s the submission of the form (the Default
action). prevent
提交表单( Default
操作)。
return false;
is for older versions of Internet Explorer, because they don't support e.preventDefault();
适用于旧版本的Internet Explorer,因为它们不支持
e.preventDefault();
. 。 Modern browsers ignore
return false;
现代浏览器忽略
return false;
. 。
When a user presses enter, the form will be submitted. 当用户按Enter键时,将提交表单。 You'll have to look for the
onsubmit
event of the form, rather than using the onclick
event of the button. 您必须查找表单的
onsubmit
事件,而不是使用按钮的onclick
事件。
<form ... onsubmit="get();">
...
</form>
Now you also have to prevent that the page actually submits (because you did it with AJAX). 现在你还必须防止页面实际提交(因为你用AJAX做过)。 Add
return false;
添加
return false;
at the end of the function get()
. 在函数
get()
的末尾。
It is better practice to assign the event using jQuery (since you are using it anyway), with the on()
method. 最好使用jQuery(因为你
on()
使用它)使用on()
方法分配事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.