0

下面的代码从表单中获取输入并从处理程序中获取结果。此电子邮件发送并正常工作;但是,我的代码是否不正确,因为我有提交按钮而不是按钮?我认为这没关系,因为我在 click 函数中返回 false。也许使用按钮值会是一个更好的主意,并在表单中取出动作,因为它已经在 ajax 中?

<div id="result">
</div>
<form action="handler.php" id="contact-form">
    <input type="text" name="name" class="clear">
    <input type="text" class="clear">
    <textarea name="message" class="clear">
    </textarea>
    <input type="submit" value="Send" id="submit-form">
</form>
$("#submit-form").click(function() {
    $.ajax({
        type: "POST",
        url: "handler.php",
        data: $("#contact-form").serialize(),
        success: function(response) {
            $('#result').html(response);
        }
    });
    return false;
});
4

1 回答 1

1

The form can be sumbited not only by clicking the submit button, but by also pressing the Enter key while focused on an input type text or by typing in the console something like: document.forms['your_form'].submit();. Therefore, you must add the event on the form element, like this:

$("#your_form_id").on("submit", function (e) {
    e.preventDefault();
    e.returnValue = false;

    // your code here

    return false;
})
于 2013-05-18T10:23:37.313 回答