1

我的 onSubmit 表格正在调用:

onsubmit="validate(this); return false;"

验证()如下:

function validate(obj) {
    $.ajax({
        url : "ajax/validate_check.php",
        type : "POST",
        data : $("#" + obj.id).serialize(),
        success : function(data) {
            $('#' + obj.id + ' :input.form_errors').removeClass('form_errors')
            data = $.parseJSON(data);
            if(data['error_count'] >= 1) {
                $.each(data, function(i, item) {
                    $('#' + i).addClass('form_errors');
                });
            } else {
                $('#' + obj.id).submit();
            }
        }
    });
}

当我有 0 个错误时,它正在尝试提交表单,但我得到了一个无限循环。我意识到它正在发生,因为我的 onSubmit 再次调用了该函数。准备好后如何实际提交表格?解决这个问题的正确方法是什么?

4

2 回答 2

1

您的验证函数应根据错误返回 true 或 false。

  onsubmit = "return validate(this)"

  function validate(obj){
     ...
     if(data['error_count'] >= 1) {
            $.each(data, function(i, item) {
                $('#' + i).addClass('form_errors');
            });
            return false; //stop submitting
        } else {
            return true;//continue submitting
        }
  }

虽然,由于您使用的是 jquery:

     $("#formid").submit(function(){
           //your validation code
     });

可能更好。

查看此页面了解更多详情。有一个很好的例子。

于 2013-03-23T17:28:27.817 回答
0

You are already submitting the form for validation.

On } else { you can't submit it again, as you noticed. You should call a function to submit it to whatever_process_the_validated_data.php

Though I'd suggest having the same .php to validate and process data - a class or function to each. That way you can:

$('.forms_that_need_validation').submit(function() {
$.ajax({
    url : "ajax/data_validation_and_processing.php",
    type : "POST",
    data : $(this).serialize(),
    success : function(data) {
        $(this + ' :input.form_errors').removeClass('form_errors')
        data = $.parseJSON(data);
        if(data['error_count'] >= 1) {
            $.each(data, function(i, item) {
                $('#' + i).addClass('form_errors');
            });
        } else {
            location.reload();
        }
    }
});
return false;
});

What happens is, if the data fails to be validated, it returns an error - you should code you .php in order not to process the data if it's not validated. Otherwise, the data was validated and processed already, then it just reloads the page.

于 2013-03-23T17:51:49.550 回答