简体   繁体   English

Jquery AJAX DELETE 请求也在同一表单上触发 POST 请求

[英]Jquery AJAX DELETE request is also triggering a POST request on the same form

I have a form wrapped around a table我有一个包裹在桌子上的表格

                <form id="project-form">
                    <table id="project-table" class="table table-striped table-inverse table-responsive">
                        <caption>Projects</caption>
                        <thead class="thead-inverse">
                            <tr>
                                <th scope="col">#</th>
                                <th scope="col">Project name</th>
                                <th scope="col">Description</th>
                                <th scope="col">Estimated time (min)</th>
                                <th scope="col">Actual time (min)</th>
                                <th scope="col">Add task</th>
                                <th scope="col">Delete project</th>
                            </tr>
                        </thead>
                        <tbody id="project-body">


                        </tbody>
                    </table>
                </form>

This table is populated via a AJAX GET request此表通过 AJAX GET 请求填充

function getProjects() {
  $.ajax({
    method: 'GET',
    dataType: 'json',
    url: 'http://localhost/WBS/php/api/requests/get.php?function=project',
    success: (response) => {
      $.each(response, function () {
        $.each(this, function (index, value) {
          console.log(value);
          $('#project-body').append(
            `
            <tr>
                <td>
                  <input class="form-control" type="hidden" name="projectid" id="projectid  value="${value.projectid}">
                  ${value.projectid}
                </td>
                <td>
                  <input class="form-control" type="text" name="projectName" id="projectName" value="${value.title}">
                </td>
                <td>
                  <input class="form-control" type="text" name="description" id="description"  value="${value.description}">
                </td>
                <td>
                  <input class="form-control" type="text" name="estimatedTime" id="estimatedTime"  value="${value.Estimated_time}">
                </td>
                <td>
                  <input class="form-control" type="text" name="actualTime" id="actualTime"  value="${value.Actual_time}">
                </td>
                <td>
                  <a id="addTask" class="btn btn-info" href="Overview.html?id=${value.projectid}" role="button">
                    <i class="fa fa-angle-right" aria-hidden="true"> </i> Add task
                  </a>
                </td>
                <td>
                  <button type="submit" id="deleteProject" name="deleteProject" class="btn btn-danger" value="${value.projectid}" >
                    <i class="fa fa-angle-right" aria-hidden="true"> </i> Delete project
                  </button>
                </td>
            </tr>

            `
          );
        });
      });
    },
    error: () => {
      console.error('Something went wrong with the getProjects function');
    },
  });
}

I would like to call the delete function on this button click我想在这个按钮上调用删除 function 点击

               <button type="submit" id="deleteProject" name="deleteProject" class="btn btn-danger" >
                    <i class="fa fa-angle-right" aria-hidden="true"> </i> Delete project
                  </button>

the function I call on said button is this function 我打电话说按钮是这个

function deleteProject() {
  let id = $(this).find('#projectid').val();

  $.ajax({
    type: 'DELETE',
    url: 'http://localhost/WBS/php/api/requests/delete.php',
    data: { id: id },
    success: () => {
      $('#alertDanger').fadeIn(() => {
        setTimeout(() => {
          $('#alertDanger').fadeOut();
        }, 5000);
      });
    },
    error: () => {
      $('#alertDangerFailed').fadeIn(() => {
        setTimeout(() => {
          $('#alertDangerFailed').fadeOut();
        }, 5000);
      });
    },
  });
}

in document.ready I handle the onclick event在 document.ready 我处理 onclick 事件

  $('#deleteProject').on('click', () => {
    deleteProject();
  });

now the problem arrives when I click on the deleteproject button, because my form has the ability to also upload new projects, the deleteproject submit event also triggers the POST call which is binded under this onclick event现在当我点击deleteproject按钮时问题就来了,因为我的表单也可以上传新项目,deleteproject提交事件也触发了绑定在这个onclick事件下的POST调用

  $('#saveProjects').on('click', () => {
    uploadProjects();
  });

EDIT: A fixed it by using this编辑:通过使用它来修复它


  $(document).on('click', '#deleteProject', () => {
    deleteProject();
  });

as onclick handler from -> Jquery button click event not firing作为 onclick 处理程序 -> Jquery 按钮单击事件未触发

As Kohaku answered, this is a default behaviour of <button type="submit"></button so you have do prevent it somehow.正如Kohaku回答的那样,这是<button type="submit"></button的默认行为,因此您必须以某种方式阻止它。 One possible solution to do it is change the button type from submit to button , should be like:一种可能的解决方案是将按钮类型从submit更改为button ,应该如下所示:

<button type="button" id="deleteProject" name="deleteProject" class="btn btn danger">
   <i class="fa fa-angle-right" aria-hidden="true"> </i> Delete project
</button>

As you mentioned, this is the form attempting to handle the default submit behaviour which, in this instance, you do not require.正如您所提到的,这是尝试处理默认提交行为的表单,在这种情况下,您不需要。

You can override this with the preventDefault() method:您可以使用preventDefault()方法覆盖它:

$('#deleteProject').on('click', (e) => {
    e.preventDefault();
    deleteProject();
});

The answer from Alison is the cleaner option actually as it addresses the issue before it's an issue https://stackoverflow.com/a/61432452/4801692艾莉森的答案实际上是更清洁的选择,因为它在问题出现之前解决了问题https://stackoverflow.com/a/61432452/4801692

What happened in your case is you are trying to trigger event for asynchronously loaded content.在您的情况下发生的事情是您试图为异步加载的内容触发事件。 In those case cases you need to write events based on its static parent element.在这些情况下,您需要根据其 static 父元素编写事件。

  • You should not use Unique id for different elements( use as class.Here i used name attribute to trigger the call ).您不应该为不同的元素使用唯一 ID(用作 class。这里我使用名称属性来触发调用)。
  • Added return false to avoid default HTML form submit behaviour.添加了 return false 以避免默认的 HTML 表单提交行为。

The following code will help you to solve the problem.以下代码将帮助您解决问题。

$('#project-form').on('click', '[name=deleteProject]', () => {
  deleteProject();
  return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM