HTML 表单 getElementById() 为 NULL

HTML form getElementById() is NULL

免责声明:在网上进行了一些研究后,我确实尝试了一些方法来确保 DOM 在我查询之前已加载,所以请检查下面的内容,也许我没有做对了,这就是问题的来源。 我知道类似的问题已经被问过 maaaaanyyyy 次了,但在阅读了类似的回复并尝试相应地调整我的代码后,我的代码仍然无法正常工作,所以请尽可能提供帮助!

我目前正在努力处理网站中的表单。我想创建一个表单,以便管理员可以在网站的某些页面上显示一条消息。当我想获取我在表单中输入的文本时,returned 值为 NULL。然后我注意到我刚刚创建的表单实际上嵌套在另一个表单中,这是行不通的。我尝试通过删除子表单并使用 formaction 字段来绕过这个问题,但我一直有一个 NULL return 值。 (我正在为我的网站使用 Spip)。

这是网站管理部分的基础HTML代码,其中包含第一个表单

<form method="post" action="#ENV{action}" id="form1">
    <div>
    #ACTION_FORMULAIRE{#ENV{action}}
    
    [(#REM) ------------------------ Alert Message ------------------------ ]
    <INCLURE{fond=formulaires/configure_alert_message}>
    <script>
        var msg_al = document.getElementById('alert_ortho').value;
        console.log(msg_al);</script>  <!-- THIS DISPLAYS THE TEXT THAT I WANT-->

    <p class="buttons">
        [(#ENV{choix}|=={valider_seul}|non)
        <input type="submit" class="submit over" title="global_update" value="global_update" />
        <input type="reset" class="submit" title="global_delete" value="global_delete" />
        ]
        <input type="submit" class="submit" title="global_update" value="global_update" />
    </p>

    </div>
</form>

那么,这里是configure_alert_message.html。我希望消息被发送到我的页面 edit_article/html.

    <div>
        <label for="name">Alert Message :</label>
        <textarea type="text" id="alert_ortho" name="alert_message">Blablabla.</textarea>
    </div>
    <div class="button">
        <button type="submit" formaction="/edit_article.html" form="form1">Save alert message</button>
    </div>
    <p></p>

最后,这是我的 edit_article.html 文件中调用前面代码的部分(这段代码也在表单字段中,我不知道如果这可能是个问题)。我在其中添加了 jQuery ready() 以确保我的查询在加载 DOM 之后发生:

        <div style="padding:10px; margin:10px; border: 3px solid #A0A0A0; text-align: center;background: #FFFF00;"> 
            <span style="color:#FF0000;"> <strong> 
                <script>
                $(document).ready(function() {
                    // do stuff when DOM is ready
                    var msg_al = document.getElementById('alert_ortho').value;
                    console.log(msg_al); <!-- THIS RETURNS "Cannot read property 'value' of null"-->
                }); </script>
            </strong> </span> </div>
        <p class='buttons'><input type='submit' name="save" class='submit' value='save_button' /></p>

为什么当我尝试通过 document.getElementById('alert_ortho') 获取消息时,我的页?我想通过在查询之前使用 formactionready() 我不会再有这个问题了。 DOM是我做错了吗?

谢谢!

document.getElementById() 当前文档 的 DOM 中搜索具有给定 ID 的元素。

它不会在不同的HTML文档中找到元素。

当您提交表单时,其中的数据将在请求正文(对于 POST 表单)或 URL 的查询字符串中传递。您需要从那里阅读它。

请注意,客户端 JS 无法访问请求正文,因此这将需要服务器端代码。