提交前检查表单使用Ajax Django

问题描述 投票:-1回答:2

我使用Ajax将数据从表单发送到服务器。但我想在Ajax提交之前检查表单中的数据:

<form id='#id_form' onsubmit='return checkInputSubmit();' >
...
</form>

在Ajax中:

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

        $.ajax({
            type: 'POST',
            url: url,
            dataType: 'json',
            data: $('#id_form').serialize(), // serializes the form's elements.
            success: function(data) {
                if(data.result == true) {
                    //My code
                }
                else {
                    //My code
                }
            }
        });
    });

但是checkInputSubmit()无法阻止从Ajax提交。您可以为我解释并给我解决方案,在Ajax提交之前检查表单中的数据。谢谢。

ajax onsubmit
2个回答
0
投票

$('#id_form').submit(function(e)事件中,您可以在调用Ajax之前检查/编辑/返回任何您想要的东西。在Ajax中,我认为它不会起作用并且不好。 (我们只检查ajax结果,而不是输入)


0
投票

@Blurp,我通过你的帮助找到了解决方案。

 $('#id_form').validate({
    submitHandler: function(form) {
        e.preventDefault();

        $.ajax({
            type: 'POST',
            url: url,
            dataType: 'json',
            data: $('#id_form').serialize(), // serializes the form's elements.
            success: function(data) {
                if(data.result == true) {
                    //My code
                }
                else {
                    //My code
                }
            }
        });
    }
 });
© www.soinside.com 2019 - 2024. All rights reserved.