将值传递给JSON Post请求

时间:2020-10-22 00:07:55

标签: javascript json event-handling

我最初的问题是,当用户单击“撰写”按钮而不是“发送”按钮时,它正在获取值。

我现在将其更改为在用户单击发送时使用其他新功能。但是,现在它什么也没做。

有人可以告诉我我在做什么错吗?我在HTML中使用了onclick方法,然后在我的Javascript页面上创建了该函数。

HTML:

<div id="compose-view">
        <h3>New Email</h3>
        <form id="compose-form"
        method="POST">
            {% csrf_token %}
            <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" id="sendEmail" class="btn btn-primary"/>
        </form>
    </div>

JS:

const element = document.getElementById('sendEmail');
  element.addEventListener('click', function() {
    fetch('/emails', {
    method: 'POST',
    body: JSON.stringify({
      recipients: 'card51short@gmail.com',
      subject: "buglets",
      body: 'Hes a fat one'
    })
  })
  .then(response => response.json())
  .then(result => {
      // Print result
      console.log(result);
  });
  });
}

2 个答案:

答案 0 :(得分:2)

好的,在这种情况下,您需要对代码进行调查:

  1. 检查fred是否实际上是字符串,而不是undefined。另外,将其设为显式常量
  const fred = document.querySelector('#compose-subject').value // changed
  console.log(fred); // new

  fetch('/emails', {
    method: 'POST',
    body: JSON.stringify({
      recipients: 'card51short@gmail.com',
      subject: fred,
      body: 'Hes a fat one'
    })
  })
  .then(response => response.json())
  .then(result => {
      // Print result
      console.log(result);
  });
  1. 如果一切都很好,请对提取的内容进行下一步检查:
  const fred = document.querySelector('#compose-subject').value

  fetch('/emails', {
    method: 'POST',
    body: JSON.stringify({
      recipients: 'card51short@gmail.com',
      subject: fred,
      body: 'Hes a fat one'
    })
  })
  .then(response => { // edited
    console.log(response); // new
    return response.json() // edited
  }) // edited
  .then(result => {
      // Print result
      console.log(result);
  });

在此过程结束之前,您应该找到不起作用的地方

答案 1 :(得分:1)

“值”属性为非输入标签返回未定义。 尝试改用innerHTML:

fred = document.querySelector('#compose-subject').innerHTML;

通过cosole.log测试您的价值:

console.log(fred);
相关问题