【问题标题】:Ajax call inside form?Ajax 在表单内调用?
【发布时间】:2017-02-24 11:29:53
【问题描述】:

我有这个功能:

function deleteDocument(e, document_id, property_id) {
  e.preventDefault();
  $('#editDocumentLoader').css('display', 'flex');
  $.ajax({
    type: "POST",
    dataType: "json",
    url: window.location.protocol + "/profile/property/document/delete/" + document_id,
    data: {
      'document_id': document_id,
      'property_id': property_id,
      '_token': CSRF_TOKEN
    },
    cache: false
  }).done(function(response) {
    alert(response);
    if (response != "") {
      try {
        $('#document_table').html(response.data);
        $('#editDocumentLoader').hide();
      } catch (e) {
        console.log(e)
      }

    } else {
      console.log("no response");
    }
  }).fail(function(response) {
    console.log(response);
    if (response.status == 422) {
      var errors = response.responseJSON;
    }
  });
}

在我看来,form 里面有这个:

<button onclick="deleteDocument(event,{{$document->id}},{{$property->id}})"><i class="fa fa-times"></i></button>

由于某种原因,它提交了我的表单,然后我的 ajax 调用不起作用。有什么建议吗?

【问题讨论】:

  • “ajax 调用不起作用”是什么意思?它会抛出错误吗?请求是否返回错误响应?反应错了吗?
  • 它返回一个错误响应
  • 那么错误说明了什么?
  • 那你为什么说不返回错误呢?
  • url: window.location.protocol + "/profile/property/document/delete/" + document_id - 这将为您提供http:/profile/property/document/delete/123 形式的结果 url - 您真的认为尝试请求 that 有意义吗?

标签: jquery ajax


【解决方案1】:

按钮的默认类型是提交: What is the default button type?

您有两个选择: 修改函数以返回 false 并将您的 html 更改为:

<button onclick="return deleteDocument(event,{{$document->id}},{{$property->id}})"><i class="fa fa-times"></i></button>

更改按钮类型:

<button type="button" onclick="deleteDocument(event,{{$document->id}},{{$property->id}})"><i class="fa fa-times"></i></button>

【讨论】:

  • 此处的选项 1 没有任何区别。它不影响单独提交事件正在发生的事实。选项 2 是有效的。
  • 您可以取消一个带有 return false 的表单应该停止表单甚至提交甚至触发。您也可以使用 onsubmit 在表单上执行此操作,但选项一应该仍然有效。
【解决方案2】:

这几乎可以肯定是因为您没有处理表单的“提交”事件,只处理按钮的“点击”事件。

将按钮的类型属性设置为type="button",这样它就不是自动提交按钮(如果你不指定它的默认类型是“提交”,这意味着任何点击它都会导致表单的“提交" 事件也会触发。因此,您的表单正在提交并执行完整的回发并在您的 ajax 调用有机会运行之前刷新页面(或者它确实运行了,但您永远看不到结果)。

<button type="button" onclick="deleteDocument(event,{{$document->id}},{{$property->id}})"><i class="fa fa-times"></i></button>

应该修复它。

【讨论】:

  • 我添加了类型按钮,但它再次提交表单
  • 您确定页面上没有其他可能影响它的代码吗?你能制作一个演示问题的 JSFiddle 吗? type="button" 的按钮永远不会导致表单提交。
  • 好的,很好。但这是一个单独的问题。我指出的是阻止你的 ajax 甚至运行(或者至少阻止你看到结果)。更改 dataType 是为了让 ajax 调用本身工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
相关资源
最近更新 更多