【问题标题】:Why is .then not working after fetching info from a form?为什么 .then 在从表单中获取信息后不起作用?
【发布时间】:2022-08-03 20:02:52
【问题描述】:

我的javascript函数(submitEmail)应该获取用户的输入并将其发布到/emails,将输入转换为json,然后将其登录到控制台。我在每一步之后都有console.log,它没有通过获取输入,所以它告诉我该步骤已完成,但随后我收到错误:Uncaught,我不知道如何修复它。

这意味着我的函数中的.then 不起作用,我不知道为什么。我是 javascript 新手,所以我不完全确定它是如何工作的。

我该如何解决?

js:

document.addEventListener(\'DOMContentLoaded\', function () {
  ...
  // Submit form
  document.querySelector(\'#compose-form\').onsubmit = submitEmail;
});

function submitEmail() {

  console.log(\'sent\') // this is shown on the console

  fetch(\'/emails\', {
    method: \'POST\',
    body: JSON.stringify({
      recipients: document.querySelectorAll(\'#compose-recipients\'), // this gets all the recipients
      subject: document.querySelector(\'#compose-subject\'), // this gets the subject 
      body: document.querySelector(\'#compose-body\') // gets the body 
    })

  })

  console.log(\'fetched\') // this is shown on the console

    .then(response => response.json()) // this is where the error occurs

  console.log(\'converted\') // this isn\'t shown on the console

    .then(result => {
      // Print result
      console.log(result);

    });

  console.log(\'results shown\') // not shown

    .catch(error => {
      console.log(\'Error:\', error);
    });

  load_mailbox(\'sent\')

  console.log(\'sent\') // not shown

  return false
};

html:

<form id=\"compose-form\">
    <div class=\"form-group\">
        From: <input disabled class=\"form-control\" value=\"{{ request.user.email }}\">
    </div>
    <div class=\"form-group\">
        To: <input id=\"compose-recipients\" class=\"form-control\">
    </div>
    <div class=\"form-group\">
        <input class=\"form-control\" id=\"compose-subject\" placeholder=\"Subject\">
    </div>
    <textarea class=\"form-control\" id=\"compose-body\" placeholder=\"Body\"></textarea>
    <input type=\"submit\" class=\"btn btn-primary\" id=\"submit-new\" name=\"btnSubmit\" />
</form>
  • 错误肯定不止“未捕获”吗?您可以添加完整的错误吗?

标签: javascript html forms


【解决方案1】:

你不能在你的 promise 和 then 方法之间放置一个 console.log 。

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2012-12-23
    • 2014-12-03
    相关资源
    最近更新 更多