HTML5会话存储发送到服务器 [英] HTML5 session storage send to server

查看:136
本文介绍了HTML5会话存储发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我是对的,会话存储存储在客户端,只能访问一个选项卡。

If I'm right, Session Storage is stored client side and is accessible only for one tab.

如何将存储在会话存储中的信息发送到服务器?我可以使用cookie,但如果我打开2个标签,cookie将被第二个标签重写。

How can I send information stored in the session storage to the server ? I can use cookie for that, but if I open 2 tabs, the cookie will be rewrite by the second tab.

谢谢

推荐答案

可以从打开相同页面的所有选项卡中获取Storage对象(localStorage和sessionStorage)。

The Storage object (both localStorage and sessionStorage) is available from all tabs having the same page open.

但是(有些评论指出这是不正确的,但这是对文档的误解),当您打开新选项卡时,会在内部创建新的存储对象。这是第一个克隆,所以此时的内容是相同的。

However (some comment state this is not correct, but this is a misinterpretation of the documentation), when you open a new tab a new storage object is created internally. This is a clone of the first one so the content at that point is the same.

它们与该点分开处理,但是你通过收听存储 事件来同步它们在您的代码中。

They are treated separate from that point, but you synchronize them by listening to the storage event in your code.

来自 http://dev.w3.org/html5/webstorage/#the-sessionstorage-attribute :(注意规格是针对实施者的)

From http://dev.w3.org/html5/webstorage/#the-sessionstorage-attribute: (note that the specs are addressing the implementers)


当通过克隆
现有浏览上下文创建新的顶级浏览上下文时,新的浏览上下文必须以
开头,与原始的相同的会话存储区域,但是从这一点开始,两套必须
被认为是分开的,不会以任何方式在
中相互影响。 [...]当setItem(),removeItem()和clear()方法在与会话
存储区域[...]相关联的存储对象x上​​调用
时, strong>然后对于Window
对象的sessionStorage属性的Storage对象与
相关联的每个Document对象,除x之外的相同存储区域发送存储通知。

也就是说,当在活动选项卡中修改存储时,会发送存储事件所有其他标签(对于相同的来源) - 但不是活动标签,当然不需要,因为这是被修改的标签。

That is to say that when a storage is modified in the active tab, a storage event is sent to all the other tabs (for the same origin) - but not the active tab which of course isn't needed as this is the one being modified.

使用事件阅读 newValue 字段,用于更新当前非活动标签中的 localSession (有)还有关于事件的 oldValue storageArea 包含受影响的Storage对象(如果同时使用本地和会话存储,则非常有用)。

Use the event to read the key and newValue fields to update the localSession in the currently inactive tab(s) (there is also the oldValue on the event). The storageArea contains the Storage object that is affected (useful if you use both local and session storage).

As到一个域 - 是的,相同的数据只能用于相同的(方案,域和端口)。

As to "one domain" - yes, the same data will only be available to the same origin (scheme, domain and port).

发送数据到服务器是完全可能的。存储在存储(会话和本地)中的所有内容都存储为字符串。我建议编码它(JSON是必需,因为它已经存储为字符串)。使用f.ex:

Sending the data to server is fully possible. Everything stored in Storage (session and local) is stored as a string. I would recommend encoding it though (JSON is not necessary as it is already stored as a string). Use f.ex:

var dataForServer = encodeURIComponent(sessionStorage.getItem(myKey));

然后将其作为表单,网址或ajax的一部分发送。

Then send it as part of a form, url or by ajax.

这篇关于HTML5会话存储发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆