通过AJAX发送表单时出错

时间:2013-09-09 08:51:55

标签: javascript jquery forms

我是jQuery的新手,我正在寻找一个解释为什么这段代码似乎不起作用。我认为这是“行动”不确定的事情。有人可以帮我理解我的错误。感谢

<script src="/jquery.validationEngine.js"></script>
<script>
    $("#contact_body").submit(function(e) {
        e.preventDefault(); // Prevents the page from refreshing

        var $this = $(this); // `this` refers to the current form element

        if ($("#contact_body").validationEngine('validate')) {
            //Post Data to Node Server
            $.post(
                $this.attr("action"), // Gets the URL to sent the post to
                $this.serialize(), // Serializes form data in standard format
                function(data) { /** code to handle response **/ },
                "json" // The format the response should be in
            );

            //Notify User That the Email Was Sent to the Server & Thanks!
            //$('#contactThanksModal').modal('show');
            $('#contactModal').modal('hide');
            alert("success"); 
        }
        else {
            //handle Invalid Email Format Error
            alert("error"); 
        }
    });
</script> 
<!--pop up contact form -->
<div id="contact" class="modal hide fade in" style="display: none;">
    <div class="modal-header">
        <a class="close" data-dismiss="modal">x</a>
        <h3>Send us a message</h3>
    </div>
    <div class="modal-body">

    <form id="contact_body"class="contact_body" name="contact_body" action="/contact">
        <label class="label" for="form_name">Your Name</label><br>
        <input type="text" name="form_name" id="form_name" class="input-xlarge"><br>

        <label class="label" for="form_email">Your E-mail</label><br>
        <input type="form_email" name="form_email" class="input-xlarge"><br>

        <label class="label" for="form_msg">Enter a Message</label><br>
        <textarea name="form_msg" class="input-xlarge"></textarea>
    </form>
</div>

<div class="modal-footer">
    <input class="btn btn-success" type="submit" value="Send!" id="submit">
    <a href="#" class="btn" data-dismiss="modal">Nah.</a>
</div>

<!-- <div id="thanks"><p><a data-toggle="modal" href="#contact" class="btn btn-primary btn-large">Modal powers, activate!</a></p></div> -->

2 个答案:

答案 0 :(得分:0)

您需要将JQuery脚本包装在

$(document).ready(function() {
    ...your_code_here...
});

然后,在尝试将事件附加到对象之前,这将等待整个文档加载。

如果没有这个,您可能会尝试将事件绑定到尚未“创建”的对象。

答案 1 :(得分:0)

您需要将代码放在文档就绪处理程序中:

<script src="/jquery.validationEngine.js"></script>
<script>
    $(function() {
        $("#contact_body").submit(function(e) {
            // your code...
        });
    });
</script> 

您的代码目前正在尝试在DOM中存在元素之前添加submit()处理程序。