hus*_*hie 5 html javascript jquery json node.js
我有一个 JSON 数组:
info = [{"name":"abc", "rank" : 1},{"name":"xyz", "rank":2},{"name":"pqr", "rank":3}];
我正在尝试使用它作为输入值传递到隐藏字段jQuery,并将其通过请求发送到服务器POST。
$('<form action="/info/saveAll" method="POST"/>')
.append($('<input type="hidden" name="info" value="' + JSON.stringify(info) + '">'))
.appendTo($(document.body))
.submit();
Run Code Online (Sandbox Code Playgroud)
在服务器端,我正在访问 as 的值info:
router.route('/saveAll')
.post((req, res) => {
let info = JSON.parse(req.body.info);
console.log(info); //SyntaxError: Unexpected end of JSON input
})
Run Code Online (Sandbox Code Playgroud)
如果我在提交之前没有stringify数组,那么typeof info仍然会返回帖子内的字符串,当我尝试使用parse字符串类型时,我会收到类似的语法错误SyntaxError: Unexpected token o in JSON at position 1。
我知道这可以通过 ajax post 请求来完成,但我想要一个不涉及 ajax 请求的解决方法。
任何帮助都会很棒。
您不能简单地将 JSON 字符串连接到 HTML 中,因为它可能包含"需要引用的保留字符,例如 。只需注释掉并使用浏览器开发人员工具中的 DOM Inspector.submit()检查代码添加到 DOM 的隐藏字段即可。input您会看到该value=属性已损坏。
解决办法很简单:使用encodeURI()代替,即
.append($(
'<input type="hidden" name="info" value="' +
encodeURI(JSON.stringify(info) +
'\'>'))
Run Code Online (Sandbox Code Playgroud)
和
let info = JSON.parse(decodeURI(req.body.info));
Run Code Online (Sandbox Code Playgroud)
现在您将看到该属性在 DOM 检查器中显示为有效的 JSON 字符串。当您在隐藏元素上选择“编辑为 HTML”菜单时,input您将在该属性的 HTML 文本中看到带引号的字符串value=。
根据我使用 Firefox 的手动测试:
const info = {
test: "somestring",
html: '<input type="hidden" value="&"/>',
};
$('#demo').append($(
'<input type="hidden" value="' +
JSON.stringify(info)) +
'">'));
Run Code Online (Sandbox Code Playgroud)
生成的 HTML:
<input type="hidden" value="{" test":"somestring","html":"<input="">
Run Code Online (Sandbox Code Playgroud)
const info = {
test: "somestring",
html: '<input type="hidden" value="&"/>',
};
$('#demo').append($(
'<input type="hidden" value="' +
encodeURI(JSON.stringify(info))) +
'">'));
Run Code Online (Sandbox Code Playgroud)
生成的 HTML:
<input type="hidden" value="%7B%22test%22:%22somestring%22,%22html%22:%22%3Cinput%20type=%5C%22hidden%5C%22%20value=%5C%22&%5C%22/%3E%22%7D">
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用 HTML 实体编码/解码方法,f.ex。这个问题,但提供的答案似乎比我的解决方案更麻烦。使用 npm 模块会更容易,例如Entity。
...不要依赖 HTML 字符串解析,让 jQuery 完成所有工作。decodeURI()它还消除了在服务器端使用的需要:
const info = {
test: "somestring",
html: '<input type="hidden" value="&"/>',
},
input = $('<input type="hidden"/>')
.val(JSON.stringify(info));
$('#demo')
.append(input);
Run Code Online (Sandbox Code Playgroud)
生成的 HTML:
<input type="hidden" value="{"test":"somestring","html":"<input type=\"hidden\" value=\"&\"/>"}">
Run Code Online (Sandbox Code Playgroud)