How to transfer data structures between browser and server

笑着哭i 提交于 2019-12-13 15:07:21

问题


In the context of interactive web apps, especially those libraries utilizing technologies such as websockets, how can we transfer data structures (e.g. maps, lists, sets, etc) between the client browser and the server? The examples I've come across so far only pass strings.

Is this supported case by case dependent on the libraries used, or a more general mechanism is available?


回答1:


You can send three things over a websocket (from the client perspective):

  • Strings
  • ArrayBuffers
  • Blobs

If you have a compound Javascript data structures (hierarchy of maps and arrays) then you should use JSON to serialize them to strings and send them over the WebSocket connection as a string.

If you are interested in sending binary byte or file data over the WebSocket connection you could still serialize to a string (inefficient bandwidth-wise) or you can send the data as ArrayBuffers or Blobs.

Note 1: When sending an ArrayBuffer or Blob results in a binary WebSocket frame on the wire your server needs to support binary frames.

Note 2: The client gets to choose what type of object is returned when the server sends a binary frame. This is the binaryType property on the WebSocket object which can be set to either "arraybuffer" or "blob".

Note 3: If you browser only supports the older WebSocket Hixie protocol series (e.g. iOS Safari) then there is no binary data and you can only send and receive strings.




回答2:


The usual way is JSON or similar.



来源:https://stackoverflow.com/questions/10741743/how-to-transfer-data-structures-between-browser-and-server

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