Validate and submit a form without enter in an infinite cycle?

我有一个无限循环使用这个jQuery代码,我知道为什么,但我不知道如何解决这个问题:

<form id="submitme">
  <input value="" name="n1" id="n1" type="text"/>
  <input value="Send" type="button"/> 
</form>
<script>
  $('#submitme').bind( 'submit', function() {
       $.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
             if (data == "true")
                $('#submitme').submit();
       }); 
  });
</script>

The jQuery.validate plugin takes care of this and I would strongly recommend you using it:

$('#submitme').validate({
    rules: {
        n1: {
            remote: {
                url: 'validate.php',
                type: 'post'
            }
        }
    }
});

But if you don't want to use it another possibility is to use a global variable, like so:

$('#submitme').submit(function() {
    if (!$.formSubmitting) {
        var $form = $(this);
        $.post('validate.php', { value: $('#n1').val() }, function (data) {
            if (data == 'true') { 
                // set the global variable to true so that we don't enter
                // the infinite loop and directly submit the form
                $.formSubmitting = true;
                $form.submit();
            }
        }); 
        return false;
    }

    return true;                     
});

Just a remark: the button you have placed inside the form is not a submit button so clicking it will not trigger the submit handler. You should make it a submit button:

<input value="Send" type="submit" /> 

I am not a jQuery expert, but in Prototype, when you write an event handler for an action and you don't stop the default action, than it will be executed after all of your callback functionality was done. So by simply flipping the if-else statement you should be able to avoid a infinite loop:

$('#submitme').bind( 'submit', function(event) {
    $.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
    if (data != "true")
        // if validation has failed, prevent default action (submit)
        event.preventDefault();
    });
    // if default action was not prevented it will be executed
})

我发现这个解决方案:

<form id="submitme">
  <input value="" name="n1" id="n1" type="text"/>
  <input value="Send" type="button"/> 
</form>
<script>
  $('#submitme').bind( 'submit', function() {
       if ($.data( $('#submitme' ), 'validated'))
           return true;
       $.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
             if (data == "true") {
                $.data( $('#submitme'), 'validated', true );
                $('#submitme').submit();
             }
       }); 
       return false;
  });
</script>
链接地址: http://www.djcxy.com/p/8654.html

上一篇: 从FlowDocument创建XPS文档并将其附加上

下一篇: 验证并提交表单而无需在无限循环中输入?