【问题标题】:Is it possible to POST from the same URL without refreshing the page?是否可以在不刷新页面的情况下从同一个 URL 发布?
【发布时间】:2017-04-05 01:02:11
【问题描述】:

我正在使用 ajax 来执行此操作,并且在后端使用 res.end 进行响应,但到目前为止,我只能发布一次。这是我的代码:

服务器

app.post("/awesome", passwordless.restricted({ failureRedirect: "/" }), (req, res, next) => {
  // ...do a bunch of stuff
  res.end();
});

客户

$("[data-new-save]").on("click", function () {
  $.ajax({
    url: "/awesome",
    type: "POST",
    data: awesomeDetails,
    success: function () {
      console.log("Cool beans");
      refreshContent(); // Re-renders content

      // Feedback
      $("nav").after("<div class=\"flash success\">Success!</div>");

      setTimeout(function () {
        $(".flash").remove();
      }, 5000);
    },
    error: function () {
      console.log("Welp");

      // Feedback
      $(".navigation").after("<div class=\"flash error\">Failure</div>");

      setTimeout(function () {
        $(".flash").remove();
      }, 5000);
    }
  });
});

【问题讨论】:

  • 您是说该按钮在您初次发布后不再起作用吗?或者服务器没有处理第二个请求?
  • 嗯!按钮没有响应。

标签: node.js ajax express post feathersjs


【解决方案1】:

这听起来像是事件委托的案例。我的最佳猜测是您的 refreshContent() 函数正在删除原始的 [data-new-save] 元素并创建新元素。这将导致绑定的click 事件被删除,并且它是最初调用时存在的 DOM 节点的属性。您可以通过将事件委托给未“刷新”的 DOM 节点来解决此问题,我假设 &lt;body&gt; 标记不会被重绘,只有一些子节点,所以如果您以 &lt;body&gt; 和寻找匹配 "[data-new-save]" 的选择器,它应该可以正常工作:

$('body').on('click', "[data-new-save]", function () {
   $.ajax({
    url: "/awesome",
    type: "POST",
    data: awesomeDetails,
    success: function () {
      console.log("Cool beans");
      refreshContent(); // Re-renders content

      // Feedback
      $("nav").after("<div class=\"flash success\">Success!</div>");

      setTimeout(function () {
        $(".flash").remove();
      }, 5000);
    },
    error: function () {
      console.log("Welp");

      // Feedback
      $(".navigation").after("<div class=\"flash error\">Failure</div>");

      setTimeout(function () {
        $(".flash").remove();
      }, 5000);
    }
  });
});

【讨论】:

  • 就是这样,谢谢!就在你认为你已经找到event-delegation 的时候。
【解决方案2】:

这是我用于类似的东西:

$(document).ready(function () {
    $('#myform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') ||     window.location.pathname,
            type: "GET",
            data: $(this).serialize(),
            success: function (data) {
                $("#form_output").html(data);
            },
            error: function (jXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2013-10-30
    • 2017-03-24
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多