store return json value in input hidden field

前端 未结 6 1222
予麋鹿
予麋鹿 2020-12-04 08:57

I was wondering if it\'s possible to store the return json in a hidden input field. For example this is what my json return:

[{\"id\":\"15aea3fa\",\"firstnam         


        
6条回答
  •  一个人的身影
    2020-12-04 09:34

    Although I have seen the suggested methods used and working, I think that setting the value of an hidden field only using the JSON.stringify breaks the HTML...

    Here I'll explain what I mean:

    
    

    As you can see the first double quote after the open chain bracket could be interpreted by some browsers as:

    
    

    So for a better approach to this I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we shold have something like the following:

    > encodeURIComponent(JSON.stringify({"name":"John"}))
    > "%7B%22name%22%3A%22John%22%7D"
    

    Now that value can be safely stored in an input hidden type like so:

    
    

    or (even better) using the data- attribute of the HTML element manipulated by the script that will consume the data, like so:

    Now to read the data back we can do something like:

    > var data = JSON.parse(decodeURIComponent(div.getAttribute("data-json")))
    > console.log(data)
    > Object {name: "John"}
    

提交回复
热议问题