HTTP cookie between two HTML pages

夙愿已清 提交于 2020-01-03 00:53:14

问题


I have two HTML pages. After entering few inputs users will be redirected from first page to second page. Before redirecting the user to second HTML page(using window.location="new HTML URL"), I persist few of the user inputs in cookie using document.cookie DOM API.

When I am in the second HTML page, I could not retrieve the value from this cookie. I think since document object would have changed in the new HTML page, my cookie values become inaccessible.

Can someone tell me: how do I retrieve the value from a cookie persisted by one javascript in one HTML page in other HTML page i.e cookie written by HTML A's javascript in HTML B's javascript?

I don't have any server-side code, so I could not take advantage of server-side logic. Also I am not supposed to pass the values in URL. So I need a solution on plain javascript and HTML.

If some one has a better solution please let me know. Thanks


回答1:


try to use localStorage instead of cookies,

// set your values in the first page
localStorage.setItem('itemKey', 'values');

// on the second page, retrieve them
var values = localStorage.getItem('itemKey');

you can use a jStorage plugin for cross browser behaviour.

also refer to this question for storing objects instead of strings




回答2:


JAAulde is on point with his answer.

For what the OP is trying to do something like PHP would be great, in that case I wouldn't bother with cookies in order to just pass data between two pages, that's just silly. However, if true persistence was needed and the data requirements were simple cookies would be the way to go even while using a language such as PHP.

Those are rather draconian constraints, is this a class project? That said there aren't any other ways to do what you're attempting, save for an ugly and highly insecure hack of the DOM.



来源:https://stackoverflow.com/questions/5392060/http-cookie-between-two-html-pages

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