JSON-将表单输入值作为JSON字符串传递时出错

时间:2019-05-15 15:53:52

标签: javascript json joomla3.0 custom-fields html-escape-characters

我正在使用<input type="text">存储通过JavaScript处理的表单值的集合。

在JavaScript中,值具有这种结构

{"family":"Johnsons","Johnsons":{"girls":["Anna","Bella"],"boys":["Robert"]}}

所以上面的输入看起来像是在提交表单之前

<input id="main" type="text" 
       value="{"family":"Johnsons","Johnsons":{"girls":["Anna","Bella"],"boys":["Robert"]}}">

保存表单后,我得到了

<input id="main" type="text" 
       value="{"family":"Johnsons","girls":"Anna","boys":"Robert"}">

输入的值是通过以下代码设置的,我怀疑这一定是问题所在:

// the input
var main = document.getElementById('main');
// the content structure before JSON.stringify
var content = {
  family: "Johnsons",
  Johnsons: {
    girls: [ "Ana", "Bela" ],
    boys: [ "Robert" ]
  }
};
main.value = JSON.stringify(content).replace( /\"/g, '\"');
main.setAttribute('value', main.value);

console.log(main.value);
<input id="main" type="text">

我需要一个普通的JavaScript解决方案,但谢谢您的答复。

2 个答案:

答案 0 :(得分:2)

只需字符串化即可,无需.replace()。还要注意,为输入分配了name属性,其值为"content",因此,在提交表单时,输入值将发送到服务器。

var form = document.forms.form;
var main = form.elements.main;

var content = {
  family: "Johnsons",
  Johnsons: {
    girls: ["Ana", "Bela"],
    boys: ["Robert"]
  }
};

main.value = JSON.stringify(content);

console.log(main.value);
<form id='form' action='https://www.hashemian.com/tools/form-post-tester.php' method='post' target='response'>
  <input id="main" name='content' type="text"><input type='submit'>
</form>
<iframe name='response'></iframe>

答案 1 :(得分:1)

您可以尝试 编辑

var main = document.getElementById('main');

var content = {
  family: "Johnsons",
  Johnsons: {
    girls: [ "Ana", "Bela" ],
    boys: [ "Robert" ]
  }
};
main.value = JSON.stringify(content, undefined, 2);
<input id="main"></input>

pre告诉浏览器引擎,其中的内容是预先格式化的,可以直接显示而无需进行任何修改。因此浏览器不会删除空格,换行等。代码是为了使其更具语义,并表示其中的内容是代码段。它与格式化无关。建议像这样<pre><code> /* Your code snippet here. */ </code></pre>

使用
<pre id="main"></pre>