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

标签 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 解决方案,但我感谢您的任何回复。

最佳答案

只需字符串化,无需 .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>

关于javascript - JSON - 传递表单输入值作为 json 字符串出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56153340/

相关文章:

php - 如何使用 google docs api php 插入文本

jquery - 调用 jQuery JSON 函数并传回结果有效负载

.htaccess - 我如何将不存在的 Joomla URLS 重定向到我们的 404 错误页面?

php - Joomla 是否支持 DELETE http 请求

javascript - 动态生成页面中的事件处理

javascript - 让用户在 jquery 中复制文本并重写粘贴

javascript - 使用 ReactJS 中的 AceEditor 了解光标在文本中的位置

javascript - nextProps 始终与 componentWillReceiveProps 中的 this.props 相同,即使 props 已更改

java - Android 从 URL 检索 JSON 对象

php - Joomla 插件通过渗透现有模块或组件来添加新功能