如何将编码的JSON发送到新页面并对其进行解码?

时间:2019-02-06 11:12:08

标签: javascript jquery

让我们说我有一个 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.

1 个答案:

答案 0 :(得分:1)

  

无法在“窗口”上执行“ atob”:要解码的字符串未正确编码

看看如何编码:

encodeURIComponent

您必须使用decodeURIComponent

来扭转它