Embedding JavaScript objects in a page's URL

前端 未结 2 1004
挽巷
挽巷 2020-12-20 09:04

I\'m trying to store a JavaScript object in the URL of a web page (as a JSON string), but the URL contains some characters that will not work with HTML links.

On thi

相关标签:
2条回答
  • 2020-12-20 09:24

    You need to encode and decode with JSON

    var link = document.getElementsByTagName('a')[0];
    link.addEventListener('click', function(){
        // this could also be done with location.hash = JSON.stringify(...);
        var param = JSON.stringify(['your', 'array']),
            href = '#'+this.getAttribute('href');
        href += param;
        location.href = href;
    }, false);
    
    
    // make string an object/array again
    var obj = JSON.parse(window.location.hash.substr(1));
    
    0 讨论(0)
  • 2020-12-20 09:33

    You can put a JSON string in an URL by URL-encoding it before putting it in the URL:

    encodeURIComponent(JSON.stringify(object))
    

    In your example, that would be:

    http://jsfiddle.net/tsUpC/1/show/#%5B%22Hello%22%2C%22World!%22%5D
    

    As you might guess, the opposite of encodeURIComponent is decodeURIComponent.

    0 讨论(0)
提交回复
热议问题