有关最近,提交和AJAX PUT请求的问题

时间:2018-09-18 07:16:53

标签: javascript ajax

我无法停止提交表单。这是用于上下文的html(我正在使用EJS):

<form class="edit-form" id="edit-review-form<%= review._id %>" action="/products/<%= product._id %>/reviews/<%= review._id %>" method="POST">
<div class="form-group">
    <input class="form-control" type="text" disabled value="<%= currentUser.username %>">
</div>
<div class="form-group">
    <input class="form-control" type="text" name="review[subject]" value="<%= review.subject %>" required>
</div>
<div class="form-group">
    <input type="number" name="review[rating]" id="rating" class="rating" value="<%=review.rating %>" required/>
</div>
<div class="form-group">
    <textarea class="form-control" name="review[text]" placeholder="<%= review.text %>" form="edit-review-form<%= review._id %>" rows="5" cols="70"><%= review.text %></textarea>
</div>
<div class="form-group">
</div>
<button class="reviewButton btn-edit-submit">Edit</button>

这是我的AJAX以及一个脚本,在脚本的两行之间有注释

$(".edit-form").submit(function (event) { // Why does this not? On the developers console this does selects the form, but doesn't stops it from submitting...
    event.preventDefault();
    let formData = $(this).serialize();
    let formAction = $(this).attr("action");
    // console.log(formData);
    // console.log(JSON.stringify(formData));
    $.ajaxSetup({
        headers: {"X-CSRF-Token": $("#_csrf").val()}
    });
    $.ajax({
        context: this, /* setting context for ajax callbacks*/
        url: formAction,
        data: formData,
        type: "PUT",
        dataType: "json"
        })
        .done(function(data) {
        if (data) {
            console.log("Success! = " + JSON.stringify(data));
        }
        }).fail(function(data) {
        console.log("Something went wrong: " + data.responseText);
    });
    return false;
});

var editReviews = document.getElementsByClassName('btn-edit-submit');
$('.collapse').on("shown.bs.collapse", function(){
 //triggers when div is collapse
    console.log("collapsed in"); // Works after collapse is finished
    for (var i = 0; i < editReviews.length; i++) {
        editReviews[i].addEventListener('click', function(event) { // editReviews works in the dev console and every button is selected
            event.preventDefault();
            // alert("clicked"); // This alert is working,
            // PUT Request form
            this.closest("form").submit();
        });
    }
});

此外,如果我从终端提交表单,它不会提交引发POST错误的表单(因为它实际上是一个放置请求),但是AJAX会通过,如果我单击按钮,它将提交我并启动错误。有什么想法吗?

编辑:也尝试过:

for (var i = 0; i < editReviews.length; i++) {
    editReviews[i].addEventListener('click', function(event) { // editReviews works in the dev console and every button is selected
        event.preventDefault();
        // alert("clicked"); // This alert is working,
        // PUT Request form
        this.closest("form").submit();
    });
}

但是它也不起作用。

我觉得我还需要提到,我使用.closest选择器的原因是视图文件中存在多种形式。

编辑:谢谢巴斯玛,尝试了您的建议:

var submitEditForm = function(form) {
    form.submit(function (event) { // Why does this not? On the developers console this does selects the form, but doesn't stops it from submitting...
        // console.log(this);
        let formData = $(this).serialize();
        let formAction = $(this).attr("action");
        $.ajaxSetup({
            headers: {"X-CSRF-Token": $("#_csrf").val()}
        });
        $.ajax({
            context: this, /* setting context for ajax callbacks*/
            url: formAction,
            data: formData,
            type: "PUT",
            dataType: "json"
            })
            .done(function(data) {
            if (data) {
                console.log("Success! = " + JSON.stringify(data));
            }
            }).fail(function(data) {
            console.log("Something went wrong: " + data.responseText);
        });
    });
}

var editReviews = document.getElementsByClassName('btn-edit-submit');
for (var i = 0; i < editReviews.length; i++) {
    editReviews[i].addEventListener('click', function(event) { // editReviews works in the dev console and every button is selected
        event.preventDefault();
        // alert("clicked"); // This alert is working,
        // PUT Request form
        var form = this.closest("form");
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            submitEditForm(form);
        });
    });
}

它阻止了它的提交,但是AJAX请求也没有通过,我做错了吗?

此外,如果我没有实际使用.closest()提交表单,则它确实通过POST路线提交,但事实是它提交了第一个form.edit-form,因为我对它进行了硬编码。

1 个答案:

答案 0 :(得分:1)

您不应该在form.submit()中调用submitEditForm,而应该执行AJAX代码。

此外,提交按钮的点击监听器应仅调用submitEditForm(),而不是为表单添加提交处理程序(每次单击添加时,在另一个监听器中添加事件监听器几乎总是错误的)另一个侦听器,直到您在第一次单击后提交之后,提交处理程序才起作用。

var submitEditForm = function(form) {

  // console.log(this);
  let formData = $(form).serialize();
  let formAction = $(form).attr("action");
  $.ajaxSetup({
    headers: {
      "X-CSRF-Token": $("#_csrf").val()
    }
  });
  $.ajax({
      context: form,
      /* setting context for ajax callbacks*/
      url: formAction,
      data: formData,
      type: "PUT",
      dataType: "json"
    })
    .done(function(data) {
      if (data) {
        console.log("Success! = " + JSON.stringify(data));
      }
    }).fail(function(data) {
      console.log("Something went wrong: " + data.responseText);
    });
};

$(".edit-form").submit(function(event) {
  event.preventDefault();
  submitEditForm(this);
});

var editReviews = document.getElementsByClassName('btn-edit-submit');
for (var i = 0; i < editReviews.length; i++) {
  editReviews[i].addEventListener('click', function(event) { // editReviews works in the dev console and every button is selected
    event.preventDefault();
    // alert("clicked"); // This alert is working,
    // PUT Request form
    var form = this.closest("form");
    submitEditForm(form);
  });
}