How to store data as a url parameter using javascript?

时光毁灭记忆、已成空白 提交于 2019-12-11 01:46:39

问题


I have a tabbed navigation menu and I have created hashed URLs for each tab. In one tab I have multiple information cards and a check box in the top right hand corner of each card. when this check box is checked the card's background color changes.

My objective is that when the page is refreshed or sent as a link the cards that have been checked remain checked along with the changed background color. Any help would really be appreciated.


回答1:


I think you need to use the combination of url parameter and localStorage to achive both refreshing and link requirements.

Lets say a user open your site with this url:

www.mysite.com/mypgae?tab=tab1&card1=checked&card2=unchecked&card3=checked

You read these parameters in your page javascript and will goto tab1 and mark card2 and card3 as checked and card2 as unchecked

now lets assume that the user changes the tab and some cards, you should store these changes in the localStorage and next time the user refreshed the page, at first you check the localStorage if it was empty you go for the url. But, if localStorage was not empty you give priority to localStorage and apply changes based on localStorage instead of url.

That is the only way that comes to my mind to support both url and local changes at the same time.




回答2:


You can use a function like this:

function dataToQueryString(data){
    var encoded = [];

    for(var key in data){
        // skip prototype properties
        if(!data.hasOwnProperty(key)) continue;

        // encode string properly to use in url
        encoded.push(key + '=' + encodeURIComponent(data[key]));
    }

    return '?' + encoded.join('&');
}

And use it like:

data = {
    id: 1,
    name: "John Doe"
}

url = url + dataToQueryString( data );

Or more specific for your case:

function storeCardsInQueryString(cards){
    var encoded = [];

    for(var i = 0; i < cards.length; i++){
        encoded.push('cards[]=' + cards[i]);
    }

    return '?' + encoded.join('&');
}

And use it like:

cards = [ 1, 7, 21, 22, 53 ];

url = url + storeCardsInQueryString( cards );


来源:https://stackoverflow.com/questions/34817091/how-to-store-data-as-a-url-parameter-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!