首页 > 解决方案 > 在 WordPress 中的 async/await/then Javascript 块中提交评论表单

问题描述

我有一个异步函数来验证表单的输入。如果一切正确,则应提交表格。

我尝试了以下代码,我的目标是调用异步函数,一旦完成,我将执行“then”部分,根据异步函数分类的结果,我想完成表单提交。

除了commentForm.submit()的实际代码外,一切都运行良好(原始提交事件的拦截、对异步函数的调用、评论文本的评估……)我得到一个Uncaught (in promise) TypeError: commentForm.submit is not a function error

我想我错过了一些非常明显的东西,但此时我被阻止了。

<script>
           window.onload=function() {
               var commentForm = document.getElementById('commentform');
               commentForm.addEventListener('submit', function(event){

                  async function classify(input) {
                       // checks, for simplificity let's assume we just return false
                       return false;
                  }

                   event.preventDefault();
                   const textComment = document.getElementById('comment').value;
                   classify([textComment]).then(result => {
                       if (result) {
                          alert('Your comment has been flagged and cannot be submitted');
                       }
                       else  {
                           alert('Good to go');
                           commentForm.submit();

                       }
                   })
                })

           }
        </script>

标签: javascriptwordpressformsasynchronousasync-await

解决方案


推荐阅读