我正在使用此代码将 POST 请求发送到我的服务器。出于某种原因,单击该按钮会发送两个 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);
}
});
最佳答案
我遇到了类似的问题。虽然这似乎没有必要,但我发现使用 .preventDefault()
可以解决问题。
关于javascript - 应用发送 POST 请求两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45980844/