javascript - 给定一个表单提交,如何仅在服务器首先使用有效标志响应时才提交?

标签 javascript jquery ajax

我有一个表单,带有文本输入和提交按钮。

提交时,我想首先访问服务器以查看输入是否有效,然后根据响应显示错误消息,或者如果有效,则继续表单提交。

这是我所拥有的:

$('#new_user').submit(function(e) { 
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/users/stuff",
        data: $('#new_user').serialize(),
        success: function(data){
            if (data.valid) {
                return true
            } else {
                // Show error message
                return false;
                e.preventDefault();
            }
        }
    });
});

问题是表单总是在提交,考虑到用例,正确的实现方法是什么?谢谢

最佳答案

尝试这样:

$('#new_user').submit(function(e) { 
    var $form = $(this);

    // we send an AJAX request to verify something
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/users/stuff",
        data: $form.serialize(),
        success: function(data){
            if (data.valid) {
                // if the server said OK we trigger the form submission
                // note that this will no longer call the .submit handler
                // and cause infinite recursion
                $form[0].submit();
            } else {
                // Show error message
                alert('oops an error');
            }
        }
    });

    // we always cancel the submission of the form
    return false;
});

关于javascript - 给定一个表单提交,如何仅在服务器首先使用有效标志响应时才提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9711802/

相关文章:

asp.net - ajax 自动完成扩展器不起作用

ajax - Railo Custom 505处理程序和Ajax路径

javascript - 变更检测和 Material 2

php - [PHP/JavaScript] : Call PHP file through JavaScript code with argument

javascript - 无法从 Canvas 获取图像数据,因为 Canvas 已被跨源数据污染

javascript - 下拉菜单切换

javascript - Javascript 重定向在 smarty .tpl 文件中不起作用

c# - 使用 JavaScript 将 visible 属性设置为 false 时删除空白区域

javascript - 在搜索比较中通过 jquery 在页面内排列搜索结果

php - 在 cakephp 中执行此操作的最佳方法是什么