简体   繁体   中英

how to pass data from javascript to json

I am working on a plugin for a static site that creates a sort of social link locker.

I am trying to pass data from the javascript to my json but i am having some issues. Code snippet below.

It's a bit long but i'm trying to pass the curr_page variable into the json string so that each page is shared properly. If i manually type in a static url the buttons work, if I try to pass in the page or curr_page variable, it doesn't work.

How can I pass the curr_page variable into that json string?

<script type="text/javascript">
    $(document).ready(function () {
        var curr_page = window.location.href;
        page = String(curr_page);
        console.log(curr_page);
        console.log(page);
        $("#sharer").sociallocker({
            text: {
                header: "Grab the extra resources",
                message: "Please support us, click like button below to unlock the content."
            },

            locker: {
                close: false,
                timer: 0
            },

            buttons: {   
                order: ["facebook-like", "twitter-tweet", "twitter-follow", "google-plus"]
            },

            facebook: {
                like: {
                    title: "Like",
                    url: "https://www.facebook.com/[]"
                }
            },

            twitter: {
                tweet: {
                    title: "Tweet",
                    text: "[]",
                    url: page 
                },
                follow: {
                    title: "Follow us",
                    url: "https://twitter.com/[username]"
                }
            },

            google: {
                plus: {
                    title: "google-share",
                    url: page
                }
            }

        });
    });
</script>

Well I hope I understand you right...

If you want to set / add a value to a JSON you just do it like

myJSON.myKey = "myValue";
myJSON.myKey.mySubKey = "myValue";

Thats all...

I'm not sure what do you want, but if you only want to pass the current page you can put directly url: window.location.href .

To be clear here, this is a javascript object, not a JSON string. You can pass variables or return from a function to the url: .

I can't understand why isn't working for you.

Check my Fiddle here

By passing the current page url, you are redirecting the page to itself, by providing the link to itself, in page variable.

   url: page

here, the url is referring to the current page only. and these social buttons on clicking will only reload the same page.

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