javascript - 为什么 JQuery $.post 提交两次?

标签 javascript jquery asp.net-mvc controller

为什么这会调用我的 Action 两次?对于背景,仅当用户单击表单上的其他位置时,使用 .change 才有效。当浏览器关闭时,.change 也不会触发。因此,计时器与数据脏属性检查相结合。提前致谢。

var timeoutId;
$(function() {
  var formElements = $('#myformid').find('input, select, textarea').add('[form=myformid]').not(':disabled').each(function() {
    $(this).attr('data-dirty', false).on('input propertychange change', function() {
      var changedText = $(this).val();
      var commentID = $(this).attr('id');
      clearTimeout(timeoutId);
      timeoutId = setTimeout(function() {
        // Runs 1 second (1000 ms) after the last change
        // Saving to DB Here
        $.post('@Url.Action("UpdateComment", "CommentJournal")', {
          "ChangedText": changedText,
          "commentID": commentID
        });
        $(this).attr('data-dirty', true);
      }, 1000);
    });
  });
});
//Controller
[HttpPost]
[AllowAnonymous]
public ActionResult UpdateComment(string changedText, string commentID) {
  return null;
}

最佳答案

可能是因为 inputchange 事件都被触发,changeinput 后触发超过 1000 毫秒> 触发,因为 change 仅在焦点离开控件时触发。示例:

var timerId = 0;
$("#field1").on("input change", function(event) {
  var type = event.type;
  clearTimeout(timerId);
  timerId = setTimeout(function() {
    console.log("timeout fired for '" + type + "'");
  }, 1000);
});
<p>Type something in the first field, wait at least a second, then tab out of the field:</p>
<div>
  <label>
    First field:
    <input type="text" id="field1">
  </label>
</div>
<div>
  <label>
    second field:
    <input type="text" id="field2">
  </label>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

如果您 Hook input,则无需 Hook change

关于javascript - 为什么 JQuery $.post 提交两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52557414/

相关文章:

jquery - 通过 Ajax 启动 session

asp.net - HTTP 错误 403.14 - 访问网站时出现禁止错误

javascript - 是否可以将一个对象计为 "whole"?

javascript - 使用 Javascript 的动态图像点击功能

javascript - 需要动态生成列

javascript - 外部 css、$.ajax、firefox、jquery。

javascript - 动态调整滑动菜单左侧位置

asp.net-mvc - asp.net mvc 404代码错误

javascript - js : loop through array indefinetly

javascript - 为什么 Jquery mobile 在桌面浏览器上显示移动友好的外观?