jquery 表单提交无法处理 success/error 通知

jquery form submit can't handle success/error notifications

如果使用 this js 通知库提交成功,我想显示成功通知,但它不起作用。

如果我将 new Notify({ ... }) 函数更改为一个简单的 alert("success");,那么警报就会出现...

但是如果我在浏览器的控制台中插入相同的 js 代码,那么它会显示通知...

<form action="" method="post">
    <div class="form-group">
        <label for="title"><h6>Title</h6></label>
        <input type="text" class="form-control" name="title" id="title">
    </div>
    <div class="form-group">
        <label for="content"><h6>Content</h6></label>
        <textarea class="form-control" id="content" name="content"></textarea>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary" id="edit">Save</button>
    </div>
</form>
<script>
 $("#edit").click(function() {

     var title = $("#title").val();
     var content = $("#content").val();
     $.ajax({
         type: "POST",
         url: "edit.php",
         data: {
            title: title,
            content: content
         },
         cache: false,
         success: function(data) {
            new Notify({
                status: 'success',
                title: 'Test',
                text: 'Success',
                effect: 'fade',
                speed: 300,
                customClass: null,
                customIcon: null,
                showIcon: true,
                showCloseButton: true,
                autoclose: false,
                autotimeout: 3000,
                gap: 20,
                distance: 20,
                type: 1,
                position: 'right top'
            })
         },
         error: function(xhr, status, error) {
             console.error(xhr);
         }
     });
      
});
</script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/simple-notify@0.5.5/dist/simple-notify.min.css" />
<script src="https://cdn.jsdelivr.net/npm/simple-notify@0.5.5/dist/simple-notify.min.js"></script>

您在问题下的评论中的以下声明澄清了问题:

I want to send the form's data then the page is just reloading immadiatelly and the notify doesn't showing up

问题是因为您没有对引发的事件调用 preventDefault()。因此表单仍然通过标准方式提交并发生页面重定向。当您使用 AJAX 时,您需要防止这种行为。

另请注意,将事件处理程序挂钩到 form 元素的 submit 事件而不是提交 buttonclick 事件更符合语义。试试这个:

$("form").on('submit', e => {
  e.preventDefault(); // stop form submission

  $.ajax({
    type: "POST",
    url: "edit.php",
    data: {
      title: $("#title").val(),
      content: $("#content").val()
    },
    cache: false,
    success: function(data) {
      new Notify({
        status: 'success',
        title: 'Test',
        text: 'Success',
        effect: 'fade',
        speed: 300,
        customClass: null,
        customIcon: null,
        showIcon: true,
        showCloseButton: true,
        autoclose: false,
        autotimeout: 3000,
        gap: 20,
        distance: 20,
        type: 1,
        position: 'right top'
      })
    },
    error: function(xhr, status, error) {
      console.error(xhr);
    }
  });
});