如何将recipenameinput内容转换为JSON?脚本输出异常求助
问题解决:食谱输入转JSON失败的修复方案
问题根源
你当前代码的核心问题是直接对DOM元素执行JSON.stringify,而没有获取输入框的实际输入值。DOM元素对象转JSON时只会保留可序列化的属性,所以输出了['{}']。另外HTML里还有几处标签错误和事件绑定问题。
修正后的代码
JavaScript代码
function submitrecipe(event) { // 阻止表单默认提交刷新页面的行为 event.preventDefault(); // 获取输入框的value值,而不是DOM元素本身 const recipename = document.getElementById('recipename').value; const recipe = document.getElementById('recipe').value; // 构建要转JSON的对象 const recipeData = { recipename: recipename, recipe: recipe }; const values = [JSON.stringify(recipeData)]; console.log(values); }
HTML代码
<div class="submit"> <h1>Submit a recipe</h1> <!--recipe form--> <div class="form"> <form method="post" onsubmit="submitrecipe(event)"> <label for="recipename">Write your recipe name</label> <br> <input type="text" id="recipename"> <br> <label for="recipe">Write your recipe</label> <br> <input type="text" id="recipe"> <br> <input type="submit" name="submitbutton" value="Submit Recipe"> </form> </div> </div>
关键修改点
- 从DOM元素的
.value属性获取输入内容,而不是直接使用DOM元素对象 - 给表单绑定
onsubmit事件并传入event,调用event.preventDefault()阻止页面刷新 - 修复HTML标签错误:把label里的
<h2>改成闭合的<label>,移除submit按钮无效的for属性 - 构建包含食谱名称和内容的对象后再转JSON,确保输出有效结构
内容的提问来源于stack exchange,提问作者superwar1012
相关产品推荐
相关产品推荐

