簡體   English   中英

表單未獲取更新的字段值

[英]Form not picking up updated field value

我正在嘗試在發送之前使用PGP Javascript API加密表單。 PGP部分有效,但表單不會發送表單字段的js修改值。

這是Javascript:

<script>
        function encryptForm() {
            var password = document.getElementById("form_password");
            var email = document.getElementById("form_email");

            email.setAttribute("type", "hidden");
            password.setAttribute("maxlength", "2000");
            password.setAttribute("type", "hidden");

            var form = document.forms[index];
            var password = form.elements["password"];
            var email = form.elements["password"];

            encrypt(email.value).then(function(encrypted_msg) {
                    email.value = encrypted_msg;
            });
            encrypt(password.value).then(function(encrypted_msg) {
                    password.value = encrypted_msg;
            });

            form.submit();

            return true;
        }

        function encrypt(msg) {
            if (msg.indexOf("-----BEGIN PGP MESSAGE-----") !== -1 && msg.indexOf("-----END PGP MESSAGE-----") !== -1) {
                return msg;
            } else {
                var key = `<?php printf($eassec->getPubkey('server')); ?>`;
                var publicKey = openpgp.key.readArmored(key).keys[0];
                return openpgp.encryptMessage(publicKey, msg).then(function(pgpMessage) {
                    return pgpMessage;
                });
            }
        } 
        </script>

和表單元素:

<form onSubmit="return encryptForm()" class="EASboxForm" method="post">
                                <input id="form_email" name="email" type="email" placeholder="email adress" required autofocus>
                                <input id="form_password" name="password" type="password" placeholder="password" maxlength="72" required>
                                <input name="action" type="hidden" value="connect">
                                    <input type="image" class="EASboxFormSend" src="resources/pics/icons/form_continue.svg" alt="Continue">
                            </form>

(您可以在[刪除]中對其進行實時測試-如果發送的數據不是有效的PGP消息,則PHP部分將顯示一條錯誤消息,如果一切正確,則散列密碼會顯示該電子郵件)

由於encrypt()是異步函數,因此您必須等待它完成才能提交表單。 您可以使用Promise.all()等待多個諾言完成。

Promise.all([encrypt(email.value).then(function(encrypted_msg) {
    email.value = encrypted_msg;
  }),
  encrypt(password.value).then(function(encrypted_msg) {
    password.value = encrypted_msg;
  })
]).then(function() {
  form.submit();
});

您還需要從encryptForm()函數return false ,以防止常規表單提交。

我可以看到,根據您的實現, function encrypt是一個異步函數。 但是javascript的執行流程是自上而下的。 當代碼到達提交時,這些值可能尚未准備好。 因此,您可能需要稍微更改程序流程,如下所示。

encrypt(email.value).then(function(encrypted_msg) {
  email.value = encrypted_msg;

  encrypt(password.value).then(function(encrypted_msg) {
    password.value = encrypted_msg;

    form.submit();
  });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM