如何将函数中的返回变量插入HTML表单

how to insert a return variable from a function to a HTML form

本文关键字:变量 插入 HTML 表单 返回 函数      更新时间:2023-09-26

我正在编写html表单帖子,以便使用SSO将人们重定向到网站。用户名直接从注册表中获取。但是,我不确定为什么该值不能插入到表单值中。有人能给我建议吗。非常感谢。

<html>
<head>
<body>
<script>
var username;
var test;
function submitForm() {
    document.forms["ciqForm"].submit();
}
function getUsername() {
    var WshShell = new ActiveXObject("WScript.Shell");
    username = WshShell.RegRead("HKEY_CURRENT_USER''Software''Plugin''username");
    // username = "albert@xxx.com"
    return username;
}

// document.getElementbyName('extRedirUserName').value=getUsername();
document.forms['myForm'].elements['extRedirUserName'].value=getUsername();
</script>
<body onload="submitForm()">
    <h1>Redirecting.</h1>
    <form id="myForm" name="myForm" method="POST" action="https://www.somewebsite.com">
        <input type="hidden" id="hello" name="extRedirUserName" value="" />
        <input type="hidden" name="extRedirPassword" value= "password" />
    </form>
</body>
</head>

`

也许是因为您没有使用正确的表单ID/Name?

document.forms["ciqForm"].submit();

但这里是

form id="myForm" name="myForm" method="POST"

运行时DOM尚未完全加载document.forms['myForm'].elements['extRedirUserName'].value=getUsername();

尝试将其添加为submitForm函数中的第一行(在文档已经执行之后执行)。我想您已经检查过使用此方法是否收到了用户名。

有一些更改:

        var username;
        var test;
        function submitForm() {
            document.getElementById("myForm").submit();//you can change this with your code
        }
        function getUsername() {
            var WshShell = new ActiveXObject("WScript.Shell");
            username = WshShell.RegRead("HKEY_CURRENT_USER''Software''Plugin''username");
            // username = "albert@xxx.com"
            return username;
        }

        // document.getElementbyName('extRedirUserName').value=getUsername();
        document.forms['myForm'].elements['extRedirUserName'].value=getUsername();
    submitForm();//call here
        </script>
        <body >
            <h1>Redirecting.</h1>
            <form id="myForm" name="myForm" method="POST" action="https://www.somewebsite.com">
                <input type="hidden" id="hello" name="extRedirUserName" value="" />
                <input type="hidden" name="extRedirPassword" value= "password" />
            </form>
        </body>
        </head>