English 中文(简体)
我如何阻止通过Ajax在本Laravel 8号电文中填满的表格的提交?
原标题:How do I prevent the default submission of forms loaded via Ajax in this Laravel 8 app?
The bounty expires in 5 days. Answers to this question are eligible for a +50 reputation bounty. Razvan Zamfir is looking for an up-to-date answer to this question.

我在Laravel提供了https://github.com/Ajax30/BraveCMS-2.0“rel=“nofollow noreferer”>blogging application。 8. 我目前正在努力通过 j(v3.5.0)补充comment Responses

comment-form.blade.php 我有:

<div class="form-wrapper">
  <div class="alert-box-ajax alert-box alert-box--success">
    Your comment is pending
  </div>

  <div class="alert-box-ajax alert-box alert-box--error">
    Failed to add comment!
  </div>

  <form class="commentForm" method="post" action="{{ route( comment.submit ) }}" autocomplete="off">
    @csrf
      <fieldset>
        <input type="hidden" name="article_id" value="{{ isset($article->id) ? $article->id : $article_id }}">
        <input type="hidden" name="parent_id" value="{{ $comment->id ??    }}">

        <div class="message form-field">
            <textarea name="msg" id="message" class="h-full-width" placeholder="Your Message" required></textarea>

            @error( msg )
            <p class="help-block text-danger">{{ $message }}</p>
            @enderror
        </div>
        <br>
        <input name="submit" id="submit" class="btn btn--primary btn-wide btn--large h-full-width" value="Add Comment" type="submit">
      </fieldset>
  </form>
</div>

当然,上述模板重复了每条评论,以便答复能够添加到其中的任何部分。

答复通过j Query Ajax提交:

$(".commentForm").each(function () {
    var form = $(this);
    form.validate({
        errorElement: "p",
        errorClass: "help-block text-danger",

        submitHandler: function (_form, event) {
            event.preventDefault();
            var $fields = form.find("textarea"),
                url = form.attr("action"),
                data = form.serialize();
            $.ajax({
                dataType: "json",
                type: "post",
                url: url,
                data: data,
                cache: false,
                success: function (response) {
                  if (response.status ===  success ) {
                    form.closest(".form-wrapper").find(".alert-box--success").slideDown(250).delay(2500).slideUp(250)
                        .slideDown(250)
                        .delay(2500)
                        .slideUp(250);
                  $fields.val("");
                  } else {
                    form.closest(".form-wrapper").find(".alert-box--error").slideDown(250).delay(2500).slideUp(250)
                        .slideDown(250)
                        .delay(2500)
                        .slideUp(250);
                  }
                },
                error: function (err) {    
                  console.log(err);
                },
            });
        },
    });
});

The problem

最初,每个员额最多可装载10台护卫机,其余则通过Ajax电话装在纸浆上。

如果这一办法有效,上述文字不能防止通过Ajax装载的表格的违约行为。

< 注: 问题不是提交活动,而是预防。

Questions

  1. What causes this issue?
  2. What is the most reliable solution to the problem?
问题回答

无论对每项评论采取何种形式,都属于单一评论。

$(document).on("submit", ".commentForm", function (event) {
    event.preventDefault();

    var form = $(this);
    form.validate({
      errorElement: "p",
      errorClass: "help-block text-danger",

      submitHandler: function (_form, event) {
        event.preventDefault();
        var $fields = form.find("textarea"),
          url = form.attr("action"),
          data = form.serialize();
        $.ajax({
          dataType: "json",
          type: "post",
          url: url,
          data: data,
          cache: false,
          success: function (response) {
            if (response.status ===  success ) {
              form.closest(".form-wrapper").find(".alert-box--success").slideDown(250).delay(2500).slideUp(250)
                .slideDown(250)
                .delay(2500)
                .slideUp(250);
              $fields.val("");
            } else {
              form.closest(".form-wrapper").find(".alert-box--error").slideDown(250).delay(2500).slideUp(250)
                .slideDown(250)
                .delay(2500)
                .slideUp(250);
            }
          },
          error: function (err) {
            console.log(err);
          },
        });
      },
    });
  });

一个简单的固定点是区分初始内容而不是初步内容。 让我们发挥职能,围绕你们的法典进行总结,并确保我们稍微修改你们的法典,以初步确定尚未实现的内容:

function initializeForms() {
    $(".commentForm:not(.initialized)").each(function () {
        var form = $(this);
        form.addClass("initialized"); //We initialized your form, so we mark it as such
        form.validate({
            errorElement: "p",
            errorClass: "help-block text-danger",

            submitHandler: function (_form, event) {
                event.preventDefault();
                var $fields = form.find("textarea"),
                    url = form.attr("action"),
                    data = form.serialize();
                $.ajax({
                    dataType: "json",
                    type: "post",
                    url: url,
                    data: data,
                    cache: false,
                    success: function (response) {
                      if (response.status ===  success ) {
                        form.closest(".form-wrapper").find(".alert-box--success").slideDown(250).delay(2500).slideUp(250)
                        .slideDown(250)
                        .delay(2500)
                        .slideUp(250);
                    $fields.val("");
                    } else {
                    form.closest(".form-wrapper").find(".alert-box--error").slideDown(250).delay(2500).slideUp(250)
                        .slideDown(250)
                        .delay(2500)
                        .slideUp(250);
                  }
                },
                error: function (err) {    
                  console.log(err);
                },
            });
        },
    });
});
}

确保你把这一功能放在页数上,以及当你完成“内容”时,以及你附上新的表格。

EDIT

您也需要谨慎,因为如果改变集装箱的<代码>inner Rainbow/code>,那么所有活动听众都将被摧毁。 因此,你将需要测试你的第一要素在装载下10时是否依然有效。 如果是的话,我的初步解决办法将发挥作用。 否则,您可以将初始线路改为$(......commentForm:not(初始化)”).each(功能(,删除form.addClass(“初始化”);

The issue you re experiencing is due to the fact that the jQuery .each() function and .validate() method are only applied to the elements that are present in the DOM at the time the code is run. This means that any elements (in your case, the comment forms) that are added to the DOM later (via AJAX) will not have these methods applied to them.

为了解决这一问题,你可以使用活动代表团。 活动代表团允许你随行一名活动听众,听从家长的一位,他们会向所有与选择者相匹配的后代开火,不管这些后代现在是否存在,还是将来会增加。

Here s how you can modify your jQuery code to use event delegation:

    $(document).on( submit ,  .commentForm , function(event) {
    event.preventDefault();

    var form = $(this);
    var $fields = form.find("textarea"),
        url = form.attr("action"),
        data = form.serialize();

    $.ajax({
        dataType: "json",
        type: "post",
        url: url,
        data: data,
        cache: false,
        success: function (response) {
            if (response.status ===  success ) {
                form.closest(".form-wrapper").find(".alert-box--success").slideDown(250).delay(2500).slideUp(250)
                    .slideDown(250)
                    .delay(2500)
                    .slideUp(250);
                $fields.val("");
            } else {
                form.closest(".form-wrapper").find(".alert-box--error").slideDown(250).delay(2500).slideUp(250)
                    .slideDown(250)
                    .delay(2500)
                    .slideUp(250);
            }
        },
        error: function (err) {    
            console.log(err);
        },
    });
});

The problem has already been explained in the comments. The Javascript you ve shown runs at page load, and selectors there will only ever match elements which exist at page load. If you dynamically add elements later on, that Javascript does not run agian, those selectors don t match them.

在此情况下,这意味着<代码>$(......commentForm)只适用于这些表格和在页数上存在的类别,因此只有这些表格才适用审定代码。 当你后来在网页上添加新的<代码>$(......commentForm)时,新表格在页数上运行的“共同提交文件”不会再出现,完全没有验证。 提供这些表格并不在此有任何 Java印,而是通常提交,这是你看到的情况。

为了做到这一点,你可以把你的鉴定变成你随时可以要求的职能,例如:

// Function to initialise validation on the passed form element.  
// $form is a jQuery object.  Note you now need to use $form to
// reference the form being validated, eg $form.find("textarea"), 
// $form.closest(), etc, inside the function.
function commentFormValidation($form) {
    $form.validate({
        // ... your validation code. 
        submitHandler: function (_form, event) {
            event.preventDefault();
            let $fields = $form.find("textarea");
            $.ajax({
                // ...
            });
        },
    });
}

// At page load, apply validation to each form that exists at that time
$(".commentForm").each(function () {
    commentFormValidation($(this));
});

现在,在增加人力部后,你可以积极增加新形式的验证。 你没有向我们展示增加新形式的法典,但为了示范目的,请允许我说,你对某种主式模版进行了修改。

// Pseudo/simplified code, this is just for demonstration
let $template = $( #commentForm-template );   // some master template
let $copy = $template.clone();                // create a copy
$copy.appendTo( .someContainer );             // add it to DOM somewhere
commentFormValidation($copy);                 // add validation to it

无论法律如何看待,你需要做的唯一重要部分是把新的验证职能称作新形式:

commentFormValidation($newFormJQueryObject);

供参考的类似问题:

奇怪的是,你也可以利用活动代表团这样做,尽管这是一个比喻的骗局,海事组织并不认为解决办法是站不住脚的。

首先,我们需要把活动手交给一个在页数上存在的选择人,并将是目前和今后各种形式的上级。 请打电话<代码>。 接下来,我们筛选出人,只配上你表格:

$( .someContainer ).on( submit ,  .commentForm , function(e) {
    e.preventDefault();
    // ...

现在,该集装箱内发生的任何“<编码>下限/代码”活动都会引发该手递,即使是在页数之后添加的表格也是如此。 没有必要增加单独编码,处理页数上存在的表格,这样就可以覆盖所有表格。

其次,我们显然需要增加一些法典,这些法典最初是以刚才提交的形式进行验证。 我们可以通过现有的<代码>commentFormValidation()履行这一职责:

$( .someContainer ).on( submit ,  .commentForm , function(e) {
    e.preventDefault();
    commentFormValidation($(this));
    // ...

But there s a problem. Submitting the form adds the validation, but it won t actually run the validation. So the first time you submit the form, nothing will happen, because the submit action has been intercepted by this handler, validation added, ... and that s all. It won t actually run the validation until you submit the form again!

因此,我们需要在添加后以人工方式进行验证。 您可以通过打电话valid()meth on the form -beit it don t work here, I m not ensure why.

So instead we can just manually re-submit the form, which will run the validation.

这里是展示这一代表团做法的工作平台。 检查黄色产出,以了解各个阶段的情况。

function commentFormValidation($form) {
    $form.validate({
        rules: {
            foo:  required 
        },
        submitHandler: function (_form, event) {
            event.preventDefault();
            console.log( submitHandler running );
        },
    });
}

$( .someContainer ).on( submit ,  .commentForm , function(e) {
    e.preventDefault();
    console.log( event handler running );

    // Initialise validation on this form
    commentFormValidation($(this));

    // Manually run the validation on this form - not sure why, does 
    // not work
    // $(this).valid();
    
    // Manually re-submit the form to trigger validation
    $(this).submit();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>

<div class="someContainer">
    <form class="commentForm">
        <input type="text" name="foo">
        <button>Submit</button>
    </form>
</div>




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签