difference between websocket and ajax

created at 03-05-2021 views: 2

Essentially different

ajax, namely Asynchronous JavaScript and XML, is a web development technology for creating interactive web applications;
WebSocket is a new protocol of HTML5, which realizes full-duplex communication between browser and server. Its essence is to create a TCP connection for exchanging data after handshake through the HTTP/HTTPS protocol. The server and the client communicate in real time through this TCP connection.

Different life cycles

Websocket establishes a long connection and keeps the connection in a session; while ajax is a short connection, the connection will be disconnected after the data is sent and received. 

Different usage scenarios

Websocket is generally used for real-time data interaction between front-end and back-end; whereas ajax is used for non-real-time data interaction between front-end and back-end . 

Different initiators

The ajax technology requires the client to initiate a request (the data returned by the request is viewed by the user); and the websocket server and the client can push information to each other (the content returned by the request of user A  can be accessable by not only the user A but also user B, if it is public,  Everyone can watch it). 

Different usage

ajax: 

$.ajax({
       type:"post",
       url:"http://localhost:8080/target",
       data:"state = yes",
       dataType:"json",
       success:function(data){
         ...
       }
});

websocket:

var monitor = new WebSocket("ws://"+ip+path)
onOpen(), onMessage(), onClose()
Please log in to leave a comment.