[英]How to convert HTML to JSON
I am trying to get user input from a form to update onto a webpage.我正在尝试从表单中获取用户输入以更新到网页上。 I have recently found out that JSON.stringify does not take html ID elements and that in order to do so they would need to be converted.
我最近发现 JSON.stringify 不采用 html ID 元素,因此需要转换它们。 I have found a guide here but did not help.
我在这里找到了指南,但没有帮助。 If anyone has any ideas please let me know, I would truly appreciate it:D
如果有人有任何想法,请告诉我,我将不胜感激:D
let type = document.getElementById('Type'); let html = type.outerHTML; let typeData = { html: html }; let name = document.getElementById('Name'); let html = name.outerHTML; let nameData = { html: html }; let quantity = document.getElementById('quantity'); let html = quantity.outerHTML; let quanData = { html: html }; update.addEventListener('click', _ => { fetch('/Plants', { method: 'put', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: typeData, name: nameData, quantity: quanData }) }).then(res => { if (res.ok) return res.json() }).then(response => { window.location.reload(true) }) }) server.js file where all my put route is app.put('/Plants', (req, res) => { quoteCollection.findOneAndUpdate( { type: req.body.type }, { $set: { quantity: req.body.quantity, type: req.body.type, name: req.body.name } } ).then(result => {res.json('Success')}).catch(error => console.error(error)) }); });
<h2>Update an item</h2> <form id="inventory-form"> <input type="text" placeholder="Type" name="Type" id="Type" /> <input type="text" placeholder="Name" name="Name" id="Name" /> <input type="number" placeholder="quantity" name="quantity" id="quantity" /> <button id="update-button " type="submit">Submit</button> </form>
Use formData and do not use the click event but the form submit event:使用 formData 并且不要使用点击事件,而是使用表单提交事件:
document.getElementById("inventory-form").addEventListener("submit", function(e) {
e.preventDefault();
const formData = new FormData(this);
fetch('/Plants', {
method: 'put',
body: formData
})
.then(res => {
if (res.ok) return res.json()
})
.then(response => {
// window.location.reload(true) // WHY???
})
})
<h2>Update an item</h2>
<form id="inventory-form">
<input type="text" placeholder="Type" name="Type" id="Type" />
<input type="text" placeholder="Name" name="Name" id="Name" />
<input type="number" placeholder="quantity" name="quantity" id="quantity" />
<button id="update-button" type="submit">Submit</button>
</form>
But WHY reload the page?但是为什么要重新加载页面?
Or if you need to refresh WHY use fetch?或者如果您需要刷新为什么要使用 fetch?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.