Before you see someone else's Web page opened there is a chat box, you can chat with the Internet users at the same time a simple topic, so they found the simplest way
Using JS, the client opens the page and constantly sends a request to the server to get a new message
Advantages and disadvantages of polling implemented with JavaScript:
1. Advantages: It is easy to implement, does not require any server-side specific features, and can work on all browsers.
2. Cons: This method is rarely used because it is completely non-scalable. Imagine the loss of bandwidth and the amount of resources in cases where 100 clients each issued a 2-second polling request, in which case 30% of the requests did not return data.
Code implementation: The page uses the Uediter editor, the background to store the latest news, get the latest news
Rootroom.js
var login = true;//Send request function SendRequest () {if (ueditor.hascontents ()) {Ueditor.sync (); $ ("#chatMsg"). Val ( Ueditor.getcontent ());} Input is a global variable, which is a single-line text box where users enter chat information var chatmsg = $ ("#chatMsg"). Val (); var datas= "chatmsg=" + chatmsg;$.ajax ({type: "POST", URL: "/chat", Data:datas,datatype: "Text", success:function (data) {if (data== "Nologin") {Login=false;alert ("You are not logged in, Please log in first "); window.location.href="/index.jsp ";} else{login=true;//uses the Chatarea multiline text field to display the server response text $ ("#chatArea"). HTML (data); Empty the contents of the input box $ ("#chatMsg"). Val (""); Ueditor.setcontent ("");}});} function Sendemptyrequest () {var datas= ""; $.ajax ({type: "post", url: "/chat", Data:datas,datatype: "Text", Success: function (data) {if (data== "Nologin") {Login=false;alert ("You are not logged in, please login First"); window.location.href= "/index.jsp";} else{login=true;//uses the Chatarea multiline text field to display the server response text $ ("#chatArea"). HTML (data);}}); /specify 0.8s to send the request again if (login==true) {setTimeout ("sendemptyrequest ()", 800);}} function Enterhandler (event) {//Get the user to click on the keyboard "key value" var keycode = event.keycode? Event.keyCode:event.which Event.which:event.charcode;//If the return key is (keycode = =) {SendRequest ();}}
Simple chat box with JS implementation only