Как отправить форму с пользовательскими переменными через Javascript? - PullRequest
0 голосов
/ 14 апреля 2019

У меня есть форма, которую я использую для выполнения операций входа в систему.При нажатии на кнопку submit необходимо выполнить следующие действия.

  1. Подключиться к firebase с помощью javascript и аутентифицировать пользователя.
  2. Получить адрес электронной почты текущего пользователя.
  3. отправьте электронное письмо на servlet через POST, так же, как работает отправка, когда вы нажимаете кнопку 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,Как я могу это сделать?

Обновление 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;

            }

Ответы [ 2 ]

1 голос
/ 14 апреля 2019

Вы можете сделать это как:

Получив данные в коде ниже, отправьте 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

0 голосов
/ 14 апреля 2019

Вы можете отправить данные формы POST на любой сервер с помощью простого вызова AJAX. Пожалуйста, смотрите следующие ссылки для получения дополнительной информации о том, как POST-данные, используя AJAX.

Любые другие вопросы, пожалуйста, дайте мне знать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...