【问题标题】:how to send encoded JSON to new page and decode it?如何将编码的 JSON 发送到新页面并解码?
【发布时间】:2019-02-06 19:20:16
【问题描述】:

假设我有一个 JSON {"ID":"1","Name":"XYZ"} 我想对此数据进行编码并将其发送到新页面,例如 new.html 并将此数据显示为 ID: 1 Name: XYZ。我怎样才能做到这一点?

到目前为止,我已经尝试过:

url = 'new.html?' + encodeURIComponent(window.btoa(JSON.stringify(str)));
document.location.href = url;

此代码在我的 first.html 脚本标记中。在我的 new.html 中,我尝试了这个:

<div id='here'></div>
        <script>
            window.onload = function () {
                var url = document.location.href,
                    params = url.split('?')[1].split('&'),
                    data = {}, tmp;
                    console.log(JSON.parse(window.atob(params)));
                for (var i = 0, l = params.length; i < l; i++) {
                    tmp = params[i].split('=');
                    data[tmp[0]] = tmp[1];
                }
                document.getElementById('here').innerHTML = data.id;
            }    
        </script>

但在 console.log 中我收到一个错误:Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

【问题讨论】:

  • btoa 毫无意义,但不应妨碍您实现目标。有什么问题?
  • 嗨@Quentin,我已经更新了我的问题。请检查。
  • 如果对象只有一维,您可以将所有参数作为键值对添加到 url:url?param1=value1&param2=value2...
  • 实际上@SergioTx 这个数据来自网络服务,所以我不知道会从那里返回什么数据。

标签: javascript jquery


【解决方案1】:

在 'Window' 上执行 'atob' 失败:要解码的字符串没有正确编码

看看你是如何编码的:

encodeURIComponent

你必须用decodeURIComponent来扭转它

【讨论】:

  • 我所做的是用JSON.parse(decodeURIComponent(params) 替换了这一行:JSON.parse(window.atob(params),它给了我一个错误,所以我删除了JSON.parse 抱歉,我以为数据被解码了但是当我在调试中看到时我意识到它没有。对不起,这是我的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 2020-01-01
  • 2016-02-16
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多