Embedding JavaScript objects in a page's URL

前端 未结 2 1006
挽巷
挽巷 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: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.

提交回复
热议问题