【问题标题】:How to submit a form with custom variables via Javascript?如何通过 Javascript 提交带有自定义变量的表单?
【发布时间】:2019-04-14 22:21:35
【问题描述】:

我有一个用于执行登录操作的表单。单击submit 按钮时,它应该执行以下操作。

  1. 使用 javascript 与 firebase 连接并对用户进行身份验证。
  2. 获取当前用户的邮箱。
  3. 通过POST 将电子邮件提交至servlet,就像单击submit 按钮时的提交方式一样。

下面是代码

function toggleSignIn() 
            {
                if (firebase.auth().currentUser) 
                {
                    // [START signout]
                    window.location.href = 'LoadSellPendingApprovals'
                    //firebase.auth().signOut();
                    // [END signout]
                } else {
                    var email = document.getElementById('email').value;
                    var password = document.getElementById('password').value;
                    if (email.length < 4) {
                        alert('Please enter an email address.');
                        return;
                    }

                    if (password.length < 4) {
                        alert('Please enter a password.');
                        return;
                    }

                    // Sign in with email and pass.
                    // [START authwithemail]
                    firebase.auth().signInWithEmailAndPassword(email, password).then(function(firebaseUser) 
                    {
                        var email = firebase.auth().currentUser.email;
                        alert(email);
                        window.location.href = 'LoadSellPendingApprovals'
                    })

                    .catch(function(error) 
                    {
                        // Handle Errors here.
                        var errorCode = error.code;
                        var errorMessage = error.message;
                        // [START_EXCLUDE]
                        if (errorCode === 'auth/wrong-password') 
                        {
                            alert('Wrong password.');
                        } else {
                            alert(errorMessage);
                        }
                        console.log(error);
                        document.getElementById('quickstart-sign-in').disabled = false;
                    // [END_EXCLUDE]
                    });

                // [END authwithemail]
                }
                document.getElementById('quickstart-sign-in').disabled = true;

            }

表格

 <form id="login-form" class="form" action="" method="post">
                                    <div class="form-group">
                                        <input type="text" name="email" id="email" class="form-control login-input" placeholder="username">
                                    </div>
                                    <div class="form-group">
                                        <input class="form-control login-input" type="password" placeholder="Password" id="password" name="password">
                                        <i id="open" class="fa fa-eye fa-2x"></i>
                                        <i id="closed" class="fa fa-eye-slash fa-2x"></i>
                                    </div>
                                    <div class="form-group">
                                        <input type="submit" id="quickstart-sign-in" name="quickstart-sign-in" class="form-control btn btn-info btn-md login-bt" value="Login" onclick="toggleSignIn()">
                                    </div>
                                    <div class="form-group text-center forgot">
                                        <a href="#">Forgot username</a> / <a href="#">password?</a>
                                    </div>
                                </form>

我可以通过firebase获取用户身份验证,获取当前用户的电子邮件,但我无法通过POST将电子邮件提交给另一个servlet。我该怎么做?

更新 1

我根据@naga - elixir - jar 更新了我的函数。下面是代码

function toggleSignIn() 
{
    if (firebase.auth().currentUser) 
    {
                    // [START signout]
                    //window.location.href = 'LoadSellPendingApprovals'
                    firebase.auth().signOut();
                    // [END signout]
                } else {
                    var email = document.getElementById('email').value;
                    var password = document.getElementById('password').value;
                    if (email.length < 4) {
                        alert('Please enter an email address.');
                        return;
                    }

                    if (password.length < 4) {
                        alert('Please enter a password.');
                        return;
                    }

                    // Sign in with email and pass.
                    // [START authwithemail]
                    firebase.auth().signInWithEmailAndPassword(email, password).then(function(firebaseUser) 
                    {
                        var email = firebase.auth().currentUser.email;
                        alert(email);
                        // console.log(email) contains email
                        const options = {
                            method: 'POST',
                            headers: {
                                // set appropriate headers, assuming json here
                                //"Content-Type": "application/json",
                                 "Content-Type": "application/x-www-form-urlencoded"
                            },
                            // form body, assuming json
                            //body: JSON.stringify(email)
                             body: `email=${email}` <-- x-www-form-urlencoded form
                        }
                        alert(email);
                        // url = your url
                        fetch(url, options)
                            .then(response => response.json())
                            .then(data => console.log(data))
      .                     catch(e => console.error(e))
                            window.location.href = 'LoadSellPendingApprovals'
                    })

                    .catch(function(error) 
                    {
                        // Handle Errors here.
                        var errorCode = error.code;
                        var errorMessage = error.message;
                        // [START_EXCLUDE]
                        if (errorCode === 'auth/wrong-password') 
                        {
                            alert('Wrong password.');
                        } else {
                            alert(errorMessage);
                        }
                        console.log(error);
                        document.getElementById('quickstart-sign-in').disabled = false;
                    // [END_EXCLUDE]
                    });
                alert('hi');
                // [END authwithemail]
                }
                document.getElementById('quickstart-sign-in').disabled = true;

            }

现在我收到以下错误

ReferenceError: url is not defined
    at (index):69
    at e.g (promise.js:829)
    at Dt (promise.js:1168)
    at Rt (promise.js:1142)
    at pt.t.Yb (promise.js:1113)
    at dt (run.js:132)

对完整答案感兴趣的人,请查看以下功能

function toggleSignIn() 
{
    if (firebase.auth().currentUser) 
    {
                    // [START signout]
                    //window.location.href = 'LoadSellPendingApprovals'
                    alert('existing user');
                    firebase.auth().signOut();
                    // [END signout]
                } else {
                    var email = document.getElementById('email').value;
                    var password = document.getElementById('password').value;
                    if (email.length < 4) {
                        alert('Please enter an email address.');
                        return;
                    }

                    if (password.length < 4) {
                        alert('Please enter a password.');
                        return;
                    }

                    // Sign in with email and pass.
                    // [START authwithemail]
                    firebase.auth().signInWithEmailAndPassword(email, password).then(function(firebaseUser) 
                    {
                        var email = firebase.auth().currentUser.email;
                        alert(email);
                        // console.log(email) contains email
                        const options = {
                            method: 'POST',
                            url: 'LoginValidator',
                            headers: {
                                // set appropriate headers, assuming json here
                                //"Content-Type": "application/json",
                                 "Content-Type": "application/x-www-form-urlencoded"
                            },
                            // form body, assuming json
                            //body: JSON.stringify(email)
                             body: `email=${email}`
                        }
                        alert(email);
                         url = 'LoginValidator'
                        fetch(url, options)
                            .then(response => response.json())
                            .then(data => console.log(data))
      .                     catch(e => console.error(e))
                            window.location.href = 'LoginValidator'
                    })

                    .catch(function(error) 
                    {
                        // Handle Errors here.
                        var errorCode = error.code;
                        var errorMessage = error.message;
                        // [START_EXCLUDE]
                        if (errorCode === 'auth/wrong-password') 
                        {
                            alert('Wrong password.');
                        } else {
                            alert(errorMessage);
                        }
                        console.log(error);
                        document.getElementById('quickstart-sign-in').disabled = false;
                    // [END_EXCLUDE]
                    });
                alert('hi');
                // [END authwithemail]
                }
                document.getElementById('quickstart-sign-in').disabled = true;

            }

【问题讨论】:

  • 取回邮件后,通过AJAXfetch API等发送POST请求。
  • @naga-elixir-jar 谢谢。我来自 Java 背景,对 Javascript 没有明确的想法。那么你能告诉我如何按照你的建议去做吗?

标签: javascript html firebase firebase-authentication


【解决方案1】:

你可以这样做:

在下面的代码中检索数据后,发送fetch POST:

firebase.auth().signInWithEmailAndPassword(email, password)
  .then(function(firebaseUser) {
    var email = firebase.auth().currentUser.email;
    // console.log(email) contains email
    const options = {
      method: 'POST',
      headers: {
        // set appropriate headers, assuming json here
        "Content-Type": "application/json",
        // "Content-Type": "application/x-www-form-urlencoded"
      },
      // form body, assuming json
      body: JSON.stringify({ email })
      // body: `email=${email}` <-- x-www-form-urlencoded form
    }
    alert(email);
    // url = your url
    fetch(url, options)
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(e => console.error(e))
    window.location.href = 'LoadSellPendingApprovals'
})

更多关于fetch API

【讨论】:

  • 对不起,我删除了我之前的评论。我需要为要传递的参数指定一个“名称”。如何设置名称?
  • 您的意思是在fetch 通话中?作为 json 还是 urlencoded?
  • 更新了json正文的答案,使用object shorthand
  • 请检查我的更新。我正在使用urlencoded 机制,我得到了错误ReferenceError: url is not defined
  • 你必须设置 url 变量,我只是注释掉了,因为它可能是任何地方的例子,const url = http://somewebsite.com/api
【解决方案2】:

您可以使用简单的 AJAX 调用将表单数据发布到任何服务器。有关如何使用 AJAX 发布数据的更多信息,请参阅以下链接。

任何其他问题请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多