Javascript 将 JSON 字符串存储在输入字段值中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5940513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:36:07  来源:igfitidea点击:

Store JSON string in input field value

javascriptjquery

提问by bsr

How to store Json string in a hidden input field. Well, I could do it programmatically, but something wrong with escaping. Since my string is moderately long, it is hard to escape " char for all the names. Please explain how it works programmatically (phase 1), as the console output looks same.

如何将 Json 字符串存储在隐藏的输入字段中。好吧,我可以通过编程来完成,但是转义有点问题。由于我的字符串长度适中,因此很难为所有名称转义 " 字符。请解释它如何以编程方式工作(第 1 阶段),因为控制台输出看起来相同。

[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]test2.html:21 [{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}] test2.html:22 PASSED PHASE 1
jquery.min.js:16Uncaught SyntaxError: Unexpected end of input

[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]test2.html:21 [{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}] test2.html:22 PASSED PHASE 1
jquery.min.js:16Uncaught SyntaxError: Unexpected end of input

thanks,

谢谢,

bsr.

bsr。



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title> 
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
        <input type="hidden" id="jsondata" />
        <input type="hidden" id="jsondata2" value="[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]"/>


    <script >
            $(document).ready(function() {  

            myItems = [{"X":0,"Y":0,"W":0,"H":500},
                   {"X":358,"Y":62,"W":200,"H":500}]

            console.log(JSON.stringify(myItems));
            $("#jsondata").val(JSON.stringify(myItems));
            console.log(document.getElementById("jsondata").value);
            console.log("PASSED PHASE 1");

            var obj = jQuery.parseJSON($("#jsondata2").val());
            console.log(obj.length);    
            console.log("PASSED PHASE 2");           
        }); 
    </script>
</body>
</html>


Edit:

编辑:

the following code works.. not sure whether it is correct. so will mark a good explanation as answer. thanks.

以下代码有效..不确定它是否正确。所以会将一个很好的解释标记为答案。谢谢。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title> 
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
        <input type="hidden" id="jsondata" />
        <input type="hidden" id="jsondata2" value='[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]'/>


    <script >
            $(document).ready(function() {  

            myItems = [{"X":0,"Y":0,"W":0,"H":500},
                   {"X":358,"Y":62,"W":200,"H":500}]

            console.log(JSON.stringify(myItems));
            $("#jsondata").val(JSON.stringify(myItems));
            console.log(document.getElementById("jsondata").value);
            console.log("PASSED PHASE 1");

            var obj = jQuery.parseJSON($("#jsondata2").val());
            console.log($("#jsondata2").val()); 
            console.log(obj[0].H);  
            console.log("PASSED PHASE 2");           
        }); 
    </script>
</body>
</html>

采纳答案by rbawaskar

The html markup is invalid ... if you run html validator againt the first html (non working one) you will find errors on the line...

html 标记无效...如果您再次在第一个 html(非工作的)上运行 html 验证器,您会发现在线错误...

回答by guaph

You can do something like this, but it's pretty bad, HTML :

你可以做这样的事情,但它很糟糕,HTML:

<textarea id="jsondata" sytle="display:none"></textarea>

and JS

和JS

$(function(){

    var myItems = [{"X":0,"Y":0,"W":0,"H":500}, {"X":358,"Y":62,"W":200,"H":500}]

    $("#jsondata").val(JSON.stringify(myItems));

});

回答by ratchet freak

<input type="hidden" id="jsondata2" value="[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]"/>

is not correct. Use single quotes 'instead of the double quotes "in the value string to fix it (or escape the ")

是不正确的。在值字符串中使用单引号'而不是双引号"来修复它(或转义"

<input type="hidden" id="jsondata2" value="[{'X':0,'Y':0,'W':0,'H':500},{'X':358,'Y':62,'W':200,'H':500}]"/>

回答by gaRex

See answer about quotes.

请参阅有关报价的答案。

Reason is simple -- when you have this code:

原因很简单——当你有这个代码时:

[sometag someattr="qwerty"123":cxzcxz"/]

browser understands it as:

浏览器将其理解为:

[sometag someattr="qwerty"/]

And last part (123":cxzcxz") just throwing off as a junk. So for your concrete case parseJSON tries to work with just this:

最后一部分 (123":cxzcxz") 只是作为垃圾扔掉。因此,对于您的具体情况, parseJSON 尝试仅使用以下方法:

[{

But you think it`s a full string like:

但你认为它是一个完整的字符串,如:

[{"X":0,"Y":0,"W":0,"H":500},{"X":358,"Y":62,"W":200,"H":500}]

So better you should encode your json before putting in a value of hidden field on server side.

所以更好的是,你应该在服务器端输入隐藏字段的值之前对你的 json 进行编码。

回答by Hogan

Try the code below, it looks like you have an array not an object to me.

试试下面的代码,看起来你有一个数组而不是我的对象。

 myItems = { data : [{"X":0,"Y":0,"W":0,"H":500},
                     {"X":358,"Y":62,"W":200,"H":500}] };