【发布时间】: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()中将setTimeout的return存储到variable中并在调用setTimeout之前调用clearTimeout(var),可能不止一次调用。 -
也没有帮助。
标签: javascript android iphone node.js post