1

我在 Rails 5.2.2 中呈现一个搜索表单,并具有确定请求应该是 AJAX 请求还是 HTML 请求的逻辑。这是我的表单的样子:

<form id="form" action="/search" data-prev-query="test" data-remote="true" method="get">
  <input type="text" name="q" id="search_query" value="test">
</form>

如果搜索查询data-prev-query与表单上的属性不同,那么我希望表单提交是一个 HTML 请求,以便重新加载页面。否则,我希望表单提交是 AJAX 请求。data-remote这是我以编程方式从表单中删除属性的逻辑:

$("#form").find("#search_query").change(function(e)
{
  var theForm = $("#form");

  var currentSearchQuery = theForm.find("#search_query").val();
  var prevSearchQuery = theForm.data("prev-query");

  var isRemote = (currentSearchQuery === prevSearchQuery);

  if (isRemote === true)
    theForm.attr('data-remote', isRemote);
  else
    theForm.removeAttr('data-remote');
});

我已确认此代码data-remote按预期删除或添加了该属性。但是,即使data-remote删除了该属性,表单仍然作为 AJAX 请求提交。

如何让表单作为 HTML 请求提交?顺便说一句,我没有使用 Turbolinks。

4

1 回答 1

2

正如@chumakoff 在评论中分享的那样,我在这篇 SO 帖子中找到了答案。我还必须调用removeData('remote')以清除 jQuery 的内部缓存。下面是我更新的有效代码。我在添加的行旁边发表了评论。

$("#form").find("#search_query").change(function(e)
{
  var theForm = $("#form");

  var currentSearchQuery = theForm.find("#search_query").val();
  var prevSearchQuery = theForm.data("prev-query");

  var isRemote = (currentSearchQuery === prevSearchQuery);

  if (isRemote === true)
  {
    theForm.removeData('remote'); // ADDED LINE
    theForm.attr('data-remote', isRemote);
  }
  else
  {
    theForm.removeAttr('data-remote');
    theForm.removeData('remote'); // ADDED LINE
  }
});
于 2019-03-06T06:06:08.827 回答