【发布时间】:2018-01-24 23:33:20
【问题描述】:
如何在javascript中提交表单并防止默认
到目前为止,我的 html 表单 (id="contact_form") 有一个 <input id="contact_send_msg" type="submit" value="Send" name="submit">,当它被点击时,我会使用以下代码在 js 中正确捕获它:
$(document).ready(function()
{
$("#contact_form").submit(function(e)
{
e.preventDefault();
$.ajax(
{
type: this.method,
url: this.action,
data: new FormData(this),
processData: false,
contentType: false,
success: function (data)
{
if(data.localeCompare("got your message") === 0)
{
alert(data);
window.location = "index.php";
}
else
{
alert('Something went wrong, try again later');
alert(data);
}
}
});
});
});
但是后来,为了添加recaptcha,我替换了
<input id="contact_send_msg" type="submit" value="Send" name="submit">
与
<button class="g-recaptcha" data-sitekey="my key" data-callback="onSubmit">Submit</button>
所以我认为使用以下代码我可以达到相同的结果,但它不会进入$("#contact_form").submit(function(e){
function onSubmit()
{
alert("it is inside1");
$("#contact_form").submit(function(e)
{
alert("it is inside2");
e.preventDefault();
$.ajax(
{
type: this.method,
url: this.action,
data: new FormData(this),
processData: false,
contentType: false,
success: function (data)
{
if(data.localeCompare("got your message") === 0)
{
alert(data);
window.location = "index.php";
}
else
{
alert('Something went wrong, try again later');
alert(data);
}
}
});
});
}
【问题讨论】:
-
data-callback="onSubmit"不会自动将该控件上的单击事件绑定到onSubmit- 您需要将事件侦听器附加到$(".g-recaptcha")上的单击事件 -
谁投了反对票,你能解释一下吗?
-
Jaromanda 我真的不明白你的意思可以解释一下吗?当我单击它时调用该函数,所以我认为唯一剩下的就是在 javascript 中提交表单并防止默认。
标签: javascript html ajax forms