[英]Passing in values to a JSON Post request
我最初的问题是当用户点击撰写按钮而不是发送按钮时它正在获取值。
我现在已将其更改为在用户单击发送时使用不同的新功能。 但是,现在它什么也没做。
有人能告诉我我做错了什么吗? 我在 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);
});
});
}
好的,在这种情况下,您需要对代码进行调查:
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);
});
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);
});
您应该在此过程结束时找到不起作用的内容
对于非输入标签,“value”属性返回 undefined。 尝试使用 innerHTML 代替:
fred = document.querySelector('#compose-subject').innerHTML;
通过 cosole.log 测试您对 fred 的价值:
console.log(fred);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.