【问题标题】:app sends POST request twice应用发送两次 POST 请求
【发布时间】:2018-02-09 08:58:32
【问题描述】:

我正在使用此代码将 POST req 发送到我的服务器。出于某种原因,单击按钮会发送两个 POST 请求。第一个发送为/register/username/password。第二个发送到/register。问题是第二个请求总是返回 404。

我试图用postCount 条件解决它,但它仍然发送两个请求。
似乎在 Windows 或 android 上使用 chrome 时,它​​会忽略 404,它工作得很好。问题是在使用 mac 或 iOS 时,它会抛出“无法 POST /register”(因为 404)。

This is the link to the app in Heroku.

双 POST 请求日志示例:

2017-08-31T11:36:18.896946+00:00 app[web.1]: POST /register/O**R/pass 200 0.423 ms - 3
2017-08-31T11:36:18.939530+00:00 app[web.1]: POST / 404 0.770 ms - 140

请求代码:

var postCount = 0;
$("#rgstnBtn").click(function () {
    var password = $("#password").val();
    var username = $("#username").val();
    if(postCount === 0) {
        if (username && password) {
            $.post("/register/" + username + "/" + password, function (data) {
                postCount++;
                // console.log("hi");
                var status = data;
                if (data === '500') {
                    location.reload();
                    alert("username already exists");
                } else {
                    window.parent.location = "/item"
                }
            });
        } else {
            refresh();
            alert('please insert valid user name and password');
        }
    }
    function refresh() {
        setTimeout(function () {
            location.reload()
        }, 10);
    }
});

【问题讨论】:

  • 看起来您真的很喜欢触发页面重新加载。我怀疑在页面加载的其他地方发生了另一个 POST。
  • 你能不能把刷新功能移到$("#rgstnBtn").click功能外面再试一次。
  • 对不起,没用:(
  • $("#rgstnBtn").click(function () { 之前添加$("#rgstnBtn").unbind('click')。也许您确实声明了两次,然后一次单击就有两个单击事件触发器。在refresh() 中将setTimeoutreturn 存储到variable 中并在调用setTimeout 之前调用clearTimeout(var),可能不止一次调用。
  • 也没有帮助。

标签: javascript android iphone node.js post


【解决方案1】:

我遇到了类似的问题。虽然看起来没有必要,但我发现使用.preventDefault() 可以解决问题。

【讨论】:

    【解决方案2】:

    好的,伙计们,我仍然不知道是什么原因导致双重发布,但是,我使用了这个操作,问题就解决了:

     $("#rgstnBtn").attr('disabled', 'disabled');
    

    谢谢大家

    【讨论】:

      猜你喜欢
      • 2016-07-01
      • 2019-05-15
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多