Web sockets make ajax/CORS obsolete?

前端 未结 4 1489
眼角桃花
眼角桃花 2020-12-02 11:14

Will web sockets when used in all web browsers make ajax obsolete?

Cause if I could use web sockets to fetch data and update data in realtime, why would I need ajax?

4条回答
  •  爱一瞬间的悲伤
    2020-12-02 11:53

    WebSockets will not make AJAX entirely obsolete and WebSockets can do cross-domain.

    AJAX

    AJAX mechanisms can be used with plain web servers. At its most basic level, AJAX is just a way for a web page to make an HTTP request. WebSockets is a much lower level protocol and requires a WebSockets server (either built into the webserver, standalone, or proxied from the webserver to a standalone server).

    With WebSockets, the framing and payload is determined by the application. You could send HTML/XML/JSON back and forth between client and server, but you aren't forced to. AJAX is HTTP. WebSockets has a HTTP friendly handshake, but WebSockets is not HTTP. WebSockets is a bi-directional protocol that is closer to raw sockets (intentionally so) than it is to HTTP. The WebSockets payload data is UTF-8 encoded in the current version of the standard but this is likely to be changed/extended in future versions.

    So there will probably always be a place for AJAX type requests even in a world where all clients support WebSockets natively. WebSockets is trying to solve situations where AJAX is not capable or marginally capable (because WebSockets its bi-directional and much lower overhead). But WebSockets does not replace everything AJAX is used for.

    Cross-Domain

    Yes, WebSockets supports cross-domain. The initial handshake to setup the connection communicates origin policy information. The wikipedia page shows an example of a typical handshake: http://en.wikipedia.org/wiki/WebSockets

提交回复
热议问题