JavaScript - 如何打开一个新页面并将 JSON 数据传递给它?

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

JavaScript - How do I open a new page and pass JSON data to it?

javascriptjqueryjson

提问by James

I have a page called search.jsp. When the user selects a record and the presses an edit button, I would like to open a new page (in the same window) with the record data (that is stored in a json object and passed to the new page). How do I use Javascript (or jQuery) to open a new page and pass the JSON data?

我有一个名为 search.jsp 的页面。当用户选择一条记录并按下编辑按钮时,我想用记录数据(存储在 json 对象中并传递到新页面)打开一个新页面(在同一窗口中)。如何使用 Javascript(或 jQuery)打开新页面并传递 JSON 数据?

采纳答案by Ulflander

If the two pages are on the same domain, a third way is to use HTML5 localStorage: http://diveintohtml5.info/storage.html

如果两个页面在同一个域,第三种方式是使用HTML5 localStorage:http: //diveintohtml5.info/storage.html

In fact localStorage is precisely intended for what you want. Dealing with GET params or window/document JS references is not very portable (even if, I know, all browsers do not support localStorage).

事实上 localStorage 正是为你想要的。处理 GET 参数或窗口/文档 JS 引用不是很容易移植(即使我知道,所有浏览器都不支持 localStorage)。

回答by Hyman

Assuming the two pages are on the same domain, you can use the returned object created by window.open() to access (and edit) the window object of a newly opened window.

假设两个页面在同一个域中,您可以使用 window.open() 创建的返回对象来访问(和编辑)新打开的窗口的窗口对象。

回答by bonbonez

Hmm, for example, you have object

嗯,例如,你有对象

var dataObject = {
    param  : 'param',
    param2 : 'param2'
};

You can translate it into string, using JSON.stringify method

您可以使用 JSON.stringify 方法将其转换为字符串

var dataObjectString = JSON.stringify(dataObject);

Then you should use Base64 encoding to encode you data (base64 encode/decode methods can be easely found in search engines)

那么你应该使用Base64编码来编码你的数据(base64编码/解码方法可以很容易地在搜索引擎中找到)

var dataObjectBase64 = base64encode(dataObjectString);

You will get something like this

你会得到这样的东西

e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307

Then you can pass this string as a parameter:

然后您可以将此字符串作为参数传递:

iframe src="http://page.com/?data=e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307"

Finally, reverse actions on the loaded page.

最后,在加载的页面上反向操作。

回答by ncubica

You can create "on the fly" a form with a hidden/text input value this will hold the json value, then you can submit this form via javascript.

您可以“即时”创建一个带有隐藏/文本输入值的表单,这将保存 json 值,然后您可以通过 javascript 提交此表单。

Something like this...

像这样的东西...

Im using JQUERY AND UNDERSCORE(for template purpose)

我使用 JQUERY 和 UNDERSCORE(用于模板目的)

this is the template

这是模板

<form method='<%= method %>' action="<%= action %>" name="<%= name %>" id="<%= id %>" target="_blank">
    <input type='hidden' name='json' id='<%= valueId %>' />
</form>

you can then post use it on javascript

然后你可以在javascript上发布使用它

function makePost(){
    var _t = _.template("use the template here");              
    var o = {
            method : "POST",
            action :"someurl.php",
            name : "_virtual_form",
            id : "_virtual_form_id",
            valueId : "_virtual_value"
        }

    var form = _t(o); //cast the object on the template
            //you can append the form into a element or do it in memory                   
    $(".warp").append(form);        

            //stringify you json        
        $("#_virtual_value").val(JSON.stringify(json)); 
        $("#_virtual_form_id").submit();
        $("#_virtual_form_id").remove();                        
}

now you dont have to be worry about the lenght of you json or how many variables to send.

现在您不必担心 json 的长度或要发送多少个变量。

best!

最好的事物!

回答by terrymorse

Here's some very simple pure JavaScript (no HTML, no jQuery) that converts an object to JSON and submits it to another page:

这是一些非常简单的纯 JavaScript(没有 HTML,没有 jQuery),它将对象转换为 JSON 并将其提交到另一个页面:

/*
    submit JSON as 'post' to a new page
    Parameters:
    path        (URL)   path to the new page
    data        (obj)   object to be converted to JSON and passed
    postName    (str)   name of the POST parameter to send the JSON
*/
function submitJSON( path, data, postName ) {
    // convert data to JSON
    var dataJSON = JSON.stringify(data);

    // create the form
    var form = document.createElement('form');
    form.setAttribute('method', 'post');
    form.setAttribute('action', path);

    // create hidden input containing JSON and add to form
    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", postName);
    hiddenField.setAttribute("value", dataJSON);
    form.appendChild(hiddenField);

    // add form to body and submit
    document.body.appendChild(form);
    form.submit();
}

Use some PHP like this on the target page to get the JSON:

在目标页面上使用一些像这样的 PHP 来获取 JSON:

$postVarsJSON = $_POST['myPostName'];
$postVars = json_decode( $postVarsJSON );

Or, more simply for JavaScript:

或者,更简单地用于 JavaScript:

var postVars = JSON.parse( <?php $_POST['myPostName']; ?> );

回答by machineghost

If the the JSON is small enough you can just include it as a GET parameter to the URL when you open the new window.

如果 JSON 足够小,您可以在打开新窗口时将其作为 GET 参数包含在 URL 中。

Something like:

就像是:

window.open(yourUrl + '?json=' + serializedJson)

回答by immanual

Assume if your json data var data={"name":"abc"};

假设您的 json 数据 var data={"name":"abc"};

The page which sends JSON data should have the following code in the script tag.

发送 JSON 数据的页面应在脚本标记中包含以下代码。

                $.getJSON( "myData.json", function( obj ) {
                console.log(obj);
                for(var j=0;j

<obj.length;j++){
                tData[j]=obj;
                //Passing JSON data in URL
                tData[j]=JSON.stringify(tData[j]);
                strTData[j]=encodeURIComponent(tData[j]);
                //End of Passing JSON data in URL
                tr = $('\


    <tr/>
                    ');
                    //Send the json data as url parameter
                    tr.append("


    <td>" + "

        <a href=\"fetchJSON.html?jsonDATA="+strTData[j]+"\" target=\"_blank\">" +Click here+ "</a>" + "

    </td>
                    ");                 
                    }
                    });

The page which receives the JSON data should have the code.

接收 JSON 数据的页面应该有代码。

<html>
                    <head></head>
                    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
                    <body>
                        <p id="id"></p>
                    </body>
                    <script type="text/javascript">
                            function getQuery() {
                                          var s=window.location.search;
                                          var reg = /([^?&=]*)=([^&]*)/g;
                                          var q = {};
                                          var i = null;
                                          while(i=reg.exec(s)) {
                                            q[i[1]] = decodeURIComponent(i[2]);
                                          }
                                          return q;
                            }
                                        var q = getQuery();
                                        try {
                                          var data = JSON.parse(q.jsonDATA);
                                          var name=data.name;
                                          console.log(name);
                                        document.getElementById("id").innerHTML=name;
                                        } catch (err) {
                                          alert(err + "\nJSON=" + q.team);
                                        }

                            </script>
                </html>