jQuery Form插件 - 如何使ajaxForm()"直播"?

asf*_*adf 8 forms jquery partial-views

所以我将"编辑"表单转换为ajaxForm,其中包含以下内容:

$('#reviewForm').ajaxForm({
    success: function (response) {
        $('#bookReview').html(response);
    }
});
Run Code Online (Sandbox Code Playgroud)

这将返回相同的表单,必要时可以再次编辑.然而,第二个表单提交不再附加ajaxForm(),这是有道理的.

我如何确保此表单始终是ajaxForm,无论发生了多少次提交,类似于live()函数的工作方式?

Slo*_*tos 11

$('#myFormId').live('submit', function() {
    // submit the form
    $(this).ajaxSubmit();
    // return false to prevent normal browser submit and page navigation
    return false;
});
Run Code Online (Sandbox Code Playgroud)

来自http://jquery.malsup.com/form/#api的 ajaxSubmit的简单修改示例.


you*_*es0 8

从文档:

代表团

如果要启用对事件委托的支持,则需要jQuery v1.7 +

// prepare all existing and future forms for ajax submission
$('form').ajaxForm({
     delegation: true
});
Run Code Online (Sandbox Code Playgroud)


pro*_*son 7

您可以ajaxForm在响应中包含调用,例如:

<!-- the html for the form -->
<script type="text/javascript">
  $('#reviewForm').ajaxForm();
</script>
Run Code Online (Sandbox Code Playgroud)

或者您可以将其作为成功函数的一部分:

function ajaxify(response, status, xhr, form){
   var review = $('#bookReview').html(response);
   $('form#reviewForm', review).ajaxForm({
      'success': ajaxify
   });
}

$('#reviewForm').ajaxForm({
   'success': ajaxify
});
Run Code Online (Sandbox Code Playgroud)

我推荐后者.

  • 现在有一个更好的解决方案,包括将"委托"设置为true (2认同)