简体   繁体   English

为什么POST方法将两次表单数据发送到服务器?

[英]Why is POST method sending form data twice to the server?

Why is this form sending data twice? 为什么此表单两次发送数据? Also, the second time, the data is "undefined". 同样,第二次,数据是“未定义的”。

The form: 表格:

<form action="/loginPage" method="POST" >

        Username: <input type="text" id="username"> <br><br>
        Password: <input type="text" id="password"> <br><br>

        <input type="submit" id="Login" value="Login" > 

    </form>

The client-side script: 客户端脚本:

$(document).ready(function(){

    $('form').submit(function(event){

    //event.preventDefault(); This prevents from sending data twice, but     then the page doesn't redirect to "Hi, <username>"

      $.post("/loginPage",{username: $("#username").val(),password: $("#password").val()}, function(data){
            ;
        });

    });
  });

The server-side script: 服务器端脚本:

app.post('/loginPage', function(req, res) {

var username = req.body.username;
console.log("Now, "+username);
res.send("Hi, "+username);

//res.sendFile(__dirname + '/lobby.html');
});

This is the output I get when I run this code: 这是我运行此代码时得到的输出:

Hi, Sho
Hi, undefined

I'm stuck at this one for the past whole day. 我整整一天都被困在这个位置。 Please help me. 请帮我。

When you submit the first time, jQuery fires and sends the POST through AJAX. 首次提交时,jQuery会触发并通过AJAX发送POST。 The second submit is the HTML form firing. 第二个提交是HTML表单触发。 You want to stop the HTML form from submitting and use your custom handler instead. 您想停止提交HTML表单,而改用自定义处理程序。

The reason you're getting undefined is because you don't have name attributes on the inputs in your form. 之所以变得undefined是因为您的表单输入中没有name属性。

You should return false; 您应该return false; in your jQuery handler to prevent the form from firing, and do something with the response data as well. 在您的jQuery处理程序中,以防止触发表单,并对响应数据进行一些处理。

Your code is posting via ajax, but it's not preventing the ordinary browser action of posting the form. 您的代码是通过ajax发布的,但这并不妨碍普通的浏览器发布表单的动作。 You don't get any parameters from the normal form post because your <input> elements don't have "name" attributes. 由于您的<input>元素没有“名称”属性,因此您无法从普通表单中获取任何参数。

You can return false; 您可以return false; from the "submit" handler to prevent the normal form submission. 从“提交”处理程序中阻止常规表单提交。

请尝试以下操作:在表单onsubmit中返回false,以防止其提交两次<form action="/loginPage" method="POST" onSubmit="return false" >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM