简体   繁体   中英

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

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?

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

If the two pages are on the same domain, a third way is to use 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).

Hmm, for example, you have object

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

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

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)

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.

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.

Something like this...

Im using JQUERY AND UNDERSCORE(for template purpose)

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

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.

best!

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.

Something like:

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

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

/*
    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:

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

Or, more simply for JavaScript:

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

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

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

                $.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.

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM