首页 > 解决方案 > 为什么 JQuery $.post 提交两次?

问题描述

为什么这会两次调用我的操作?对于背景,使用 .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;
}

标签: javascriptjqueryasp.net-mvccontroller

解决方案


可能是因为inputchange事件都被触发,change触发后触发超过 1000 毫秒input,因为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>

如果你钩input了,就没有必要钩了change


推荐阅读