Javascript 如何在GET url查询字符串中传递Json对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33010491/
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 14:30:33  来源:igfitidea点击:

How to Pass Json object in GET url query string

javascriptjsonspring-mvcgetrequest

提问by gauti

I have a json object in javascript,

我在 javascript 中有一个 json 对象,

filters = Object {assetType: "CAR~LIGHT TRUCK", bodyType: "SEDAN~SPORT UTIL"}

I need to pass these values along with 5 more string value in query string.

我需要将这些值与查询字符串中的另外 5 个字符串值一起传递。

url = '/starHome/exportToCsv/'+tier+'/?period='+period+'&level2='+level2+'&level3='+level3+'&level4='+level4+'&filters='+filters;

window.location.href = url;when I tried to get filter parameter value in controller request.getparamter("filters");I get "[object object]"

window.location.href = url; 当我试图在控制器中获取过滤器参数值时, request.getparamter("filters");我得到“ [object object]

how can I pass this value to controller?. I have a pojo class contains all these fields. Can I make use of that class?.

如何将此值传递给控制器​​?我有一个 pojo 类包含所有这些字段。我可以使用那个类吗?

采纳答案by gauti

Thanks Everyone, I have used JSON.stringify(filters);and in controller

谢谢大家,我JSON.stringify(filters);在控制器中使用过

String filtersString = request.getParameter("filters");
Map<String,Object> result = new ObjectMapper().readValue(filtersString, HashMap.class);

Kindly reply back, if there s a better approach.

请回复,如果有更好的方法。

回答by Miguel Mesquita Alfaiate

You can encode your json string in base64 and then use it in the url:

您可以在 base64 中对 json 字符串进行编码,然后在 url 中使用它:

https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa

https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa

回答by onlymybest

You might be able to use jQuery.param()

你也许可以使用jQuery.param()

    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script type="text/javascript">
    var filters = {assetType: "CAR~LIGHT TRUCK", bodyType: "SEDAN~SPORT UTIL"};
    filters = jQuery.param( filters );
    console.log("filters ", filters );
    //filters  assetType=CAR~LIGHT+TRUCK&bodyType=SEDAN~SPORT+UTIL

    url = '/starHome/exportToCsv/'+tier+'/?period='+period+'&level2='+level2+'&level3='+level3+'&level4='+level4+'&filters='+filters;
    </script>

回答by Hyyan Abo Fakher

I found the following as the best solution so far using Javasript

我发现以下是迄今为止使用 Javasript 的最佳解决方案

var a = {a:'foo',b:[1,2,3],g: {q:"8798"}};

var b = window.btoa(JSON.stringify(a)); 

console.log(b) // output eyJhIjoiZm9vIiwiYiI6WzEsMiwzXSwiZyI6eyJxIjoiODc5OCJ9fQ

// restore b again 
console.log(JSON.parse(window.atob(b))); // output : {a:'foo',b:[1,2,3],g: {q:"8798"}}