当我在HTML中删除表单时,为什么我的WebSocket无法正常工作?

时间:2015-04-18 06:03:08

标签: javascript html websocket

我正在使用WebSocket显示某个值,该值计算有史以来对我网站的所有访问已经过了多少秒。例如,如果用户A在我的网站上花费20秒,则用户B花费30秒,而用户C花费10秒,60秒被添加到计数器。计数器不断更新。这是我的JavaScript和HTML代码。现在,我想从HTML中删除表单,但是当我这样做时,我得到了文本" [object HTMLTextAreaElement]。"我怎样才能解决这个问题并让我的网站上线?



var socket = new WebSocket('ws://echo.websocket.org');
function count() {
	if(! counter){
		var counter = 1;
	} else {
		counter = counter + 1;
	};
	socket.send(counter);
	document.getElementById('messages').innerHTML = '<li>' + message + '</li>';
}
setInterval(count, 1000);
count();
window.close() = function() {
	socket.close();
};
&#13;
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>
        WebSockets Demo
    </title>
  </head>
  <body>
    <div id="page-wrapper">
      <h1>
        WebSockets Demo
      </h1>
      <ul id="messages">
      </ul>
      <form id="message-form" action="#" method="post">
        <textarea id="message" required></textarea>
        <button type="submit">
          Send Message
        </button>
      </form>
    </div>
    <script src="app.js">
    </script>
  </body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您的代码中未定义变量message。因此,它将引用具有相应ID的HTML DOM,即<textarea id="message" required></textarea>

我假设您要显示来自echo服务器的返回消息。如果是这样,代码如下:

&#13;
&#13;
var socket = new WebSocket('wss://echo.websocket.org');
var counter = 0;
function count() {
	counter++;
	socket.send(counter);
}
socket.onmessage = function(evt){
    document.getElementById('messages').innerHTML += '<li>' + evt.data + '</li>';
};
socket.onopen = function(){
    setInterval(count, 1000);
    count();
};
window.close() = function() {
	socket.close();
};
&#13;
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>
        WebSockets Demo
    </title>
  </head>
  <body>
    <div id="page-wrapper">
      <h1>
        WebSockets Demo
      </h1>
      <ul id="messages">
      </ul>
      <form id="message-form" action="#" method="post">
        <textarea id="message" required></textarea>
        <button type="submit">
          Send Message
        </button>
      </form>
    </div>
    <script src="app.js">
    </script>
  </body>
</html>
&#13;
&#13;
&#13;