提交表单而不刷新页面ajax,php,javascript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21612197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:18:48  来源:igfitidea点击:

Submit form without refreshing page ajax,php,javascript?

javascriptphpjqueryhtmlajax

提问by Patrik Fr?hler

I want to submit a form without refreshing the page, from what I have read it should work with ajax, what am i doing wrong?

我想在不刷新页面的情况下提交表单,从我读过的内容来看,它应该可以与 ajax 一起使用,我做错了什么?

it all works with the php and stuff when I do this:

当我这样做时,这一切都适用于 php 和其他东西:

document.getElementById("msg_form").submit();

But I want it to submit without refreshing the page.

但我希望它在不刷新页面的情况下提交。

Part of Html:

Html 的一部分:

<form name="msg_form_name" id="msg_form" class="email" action="mailer.php">
<p>Your E-mail:</p>
<input id="email_form" name="email" type="text" />
<p>Amount:</p>
<input id="amount_form" name="amount" class="amount_num" type="text" maxlength="5" />
<div id="msg_txt_lenght">characters left: 38</div>
<p>Message:</p>
<input id="message_form" name="message" class="message_form_lim" type="text" >
<input type="hidden" id="storeUrl_id" name="storeUrl_form" value="Nan"></form>
</form>

Part of javascript:

部分 JavaScript:

$('#msg_form').submit(function (e) {
    e.preventDefault();

$.ajax({             
type: 'post',
url: 'mailer.php',
data: $('form').serialize(),
success: function () {
 alert('form was submitted');
}
    });

    return false;
});

Thanks in advance.

提前致谢。

EDIT: might have fixed it had it on submit but didn't send a submit

编辑:可能已经修复它提交但没有发送提交

回答by Patrik Fr?hler

Solved it just replaced:

解决它只是替换:

$('#msg_form').submit(function (e) {
    e.preventDefault();

$.ajax({             
type: 'post',
url: 'mailer.php',
data: $('#msg_form').serialize(),
success: function () {
 alert('form was submitted');
}
    });

    return false;
});

with this instead

用这个代替

$.post('mailer.php', $('#msg_form').serialize())