获取一个 json 字符串请求参数
Getting a json string request parameter
我有一个 json 对象,当它在客户端和服务器端传递请求参数时,json 字符串从 space 中断个字符。
例如:
{"id":100,"age":15,"name":"sample string"}
当它来到 request.getParameter() 时显示为这样
{"id":100,"age":15,"name":"sample
JAVA脚本
var location='MyAction.do?method=myMethod';
var form = '<input type="hidden" name="transactionId" value="'+getSession()+'" /><input type="hidden" name="myInfo" value='+JSON.stringify(myInfo)+' />';
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
JAVA
String myInfo = request.getParameter("myInfo");
只有当信息字符串具有 space characters.how 时才会发生这种情况,我可以得到完整的字符串吗?
谢谢。
您可以对您的值进行编码
value='+JSON.stringify(myInfo)+'
这将给出带有 spaces 等的原始字符串。您可以使用内置的 encodeURIComponent(string)
方法来编码您的字符串
var myInfo = {"id":100,"age":15,"name":"sample string"};
encodeURIComponent(JSON.stringify(myInfo));
此 returns 编码字符串。这不包含任何可能混淆浏览器的符号({}[space]&? 等)
%7B%22id%22%3A100%2C%22age%22%3A15%2C%22name%22%3A%22sample%20string%22%7D
然后您可以使用 decodeURIComponent(string)
对其进行解码
var request_value = decodeURIComponent('%7B%22id%22%3A100%2C%22age%22%3A15%2C%22name%22%3A%22sample%20string%22%7D');
JSON.parse(request_value);
我有一个 json 对象,当它在客户端和服务器端传递请求参数时,json 字符串从 space 中断个字符。
例如:
{"id":100,"age":15,"name":"sample string"}
当它来到 request.getParameter() 时显示为这样
{"id":100,"age":15,"name":"sample
JAVA脚本
var location='MyAction.do?method=myMethod';
var form = '<input type="hidden" name="transactionId" value="'+getSession()+'" /><input type="hidden" name="myInfo" value='+JSON.stringify(myInfo)+' />';
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
JAVA
String myInfo = request.getParameter("myInfo");
只有当信息字符串具有 space characters.how 时才会发生这种情况,我可以得到完整的字符串吗?
谢谢。
您可以对您的值进行编码
value='+JSON.stringify(myInfo)+'
这将给出带有 spaces 等的原始字符串。您可以使用内置的 encodeURIComponent(string)
方法来编码您的字符串
var myInfo = {"id":100,"age":15,"name":"sample string"};
encodeURIComponent(JSON.stringify(myInfo));
此 returns 编码字符串。这不包含任何可能混淆浏览器的符号({}[space]&? 等)
%7B%22id%22%3A100%2C%22age%22%3A15%2C%22name%22%3A%22sample%20string%22%7D
然后您可以使用 decodeURIComponent(string)
var request_value = decodeURIComponent('%7B%22id%22%3A100%2C%22age%22%3A15%2C%22name%22%3A%22sample%20string%22%7D');
JSON.parse(request_value);