我想合并两个代码“片段”,但我真的不知道该怎么做。
我设法使HTML表单输入到JSON对象中。请参阅codepen here。
当我单击“添加注释” btn时,我想获取输入值->使它们成为对象->将它们发布到我的api对象数组中。下面的图像和代码示例:
HTML到JSON
// CREATE NEW NOTES
var btn = document.getElementById('btn');
btn.addEventListener("click", function() {
var request = new XMLHttpRequest();
request.open('POST', 'https://timesheet-1172.appspot.com/af25fa69/notes');
request.setRequestHeader('Content-Type', 'application/json');
request.onload = function () {
// When I click the "Add note" btn I want to grab the input values -> make them to an object -> POST them to my api object array.
// Like
// var body = {
// 'title': form.title.value,
// 'description': form.description.value
// }
};
request.send(JSON.stringify(body));
});
这是当前的代码,让我发送一个已设置的带有对象属性的变量。见下图:
发送JSON
但是我的问题是关于如何结合这些示例,以便可以进行动态输入->将它们转换为JSON对象->将它们插入api对象数组。
如果您认为我走错了路或认为有解决方案,请随时纠正我!
如果您有任何疑问或需要澄清,请随时提出!
预先感谢!
// E
最佳答案
您可以这样组合它们(我认为这是最好的方法):
定义一个将在表单提交时执行的函数,它将创建JSON并通过ajax发送:
function formatJSONAndSend(form) {
var body = {
title: form.title.value,
description: form.description.value
};
var request = new XMLHttpRequest();
request.open('POST', 'https://timesheet-1172.appspot.com/af25fa69/notes');
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(body));
}
您可以从
HTML
调用它,例如:<form onsubmit="formatJSONAndSend(this);">
Title: <input type="text" class="form-control" name="title" placeholder="Title goes here..." /><br /> Description: <input type="text" class="form-control" name="description" placeholder="Description goes here..." /><br />
<input class="btn btn-primary" id="btn" type="submit" value="Add note">
</form>
在通过单击添加注释按钮提交表单后,它将调用
formatJSONAndSend()
函数,该函数将首先从表单中获取数据并将其放入body
对象中,然后通过POST
发送到您的Web api。这是一个工作示例:Codepen