javascript - 如何将字符串化对象添加到 url 末尾

标签 javascript json object ecmascript-6 uri

我正在尝试获取一个像这样的 json 对象:

filters = {"filters": myArray};

并将其附加到 URL 的末尾,使用:

this.router.navigate([`/devices/${productType}/${deviceCategory}/${JSON.stringify(filters)}`]);

无论如何,所以我在其他论坛上读到应该使用encodeURIComponent,所以我尝试了以下操作:

this.router.navigate([`/devices/${productType}/${deviceCategory}/${encodeURIComponent(JSON.stringify(filters))}`]);

此时我没有收到错误,但是,当我尝试从 params.paramId.filters 获取数据时,即使我使用 JSON.parse 解码或解析它,我也会得到未定义的结果(decodeURIComponent(params.paramId.filters));

如何将字符串化对象添加到 URL,然后从参数中检索它以继续使用它?

提前谢谢您!

最佳答案

编码

首先执行以下操作:

const source = new URLSearchParams(filters).toString();

并将其附加到您的网址:

encodeURIComponent(JSON.stringify(source));
<小时/>

解码

这样做:

var search = location.search.substring(1);
var filters = JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g,'","').replace(/=/g,'":"') + '"}');

关于javascript - 如何将字符串化对象添加到 url 末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57514727/

相关文章:

php - 如何在 Symfony2 中将 json 渲染成 Twig

php - Json 编码从 Ajax 中给我 null,但从正常的 php 字符串中没有给我 null

c++ - 无法将数据从txt文件写入对象

c++ - C++ 中 object->function() 和 object.function() 的区别

java - 如何从字符串中删除 '\' 字符

JavaScript 表单并计算分数

javascript - 仅将 AJAX 响应传递给数组中的当前 div

javascript - 跨域获取ajax请求抛出解析错误

python - 如何在 Python 中创建对象集合代理?

javascript - Carousel slick.js + bootstrap 列宽问题