【发布时间】:2011-10-17 09:07:00
【问题描述】:
我正在尝试使用 AJAX 将记录插入数据库。我不知道为什么,但似乎提交按钮的 onclick 标记中引用的 javascript 函数被触发了两次,因此每次点击我的数据库中都会获得两条记录。
在 JS 中放置警报,我设法找出问题在于 JS 函数被调用了两次,而不是 PHP 脚本进行了两次插入。所以,除非被问到,否则我不会发布 PHP 脚本。
这是表单的 HTML:
<form id="notify" method="post" action="add_notify.php">
Name: <input type="text" class="formname" name="name" value="" size="20"/>
Email: <input type="text" class="formname" name="email" value="" size="20"/>
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
</form>
Javascript:
$("document").ready(function() {
$("#notify").submit(function() {
processInfo();
return false;
});
});
function processInfo()
{
var errors = false;
// Validate name
var name = $("#notify [name='name']").val();
if (!name) {
errors = true;
document.getElementById('name_error').innerHTML = 'You must enter a name.';
}
var email = $("#notify [name='email']").val();
if (!email)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter an email.';
}
else
{
var validEmail = true;
validEmail = validateEmail(email);
if (!validEmail)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter a valid email address.';
}
}
if (!errors)
{
$("#notify").ajaxSubmit({success:showResult});
return false;
}
}
【问题讨论】:
标签: javascript