Events and changes in a JSP?

1

Hello. I have a jsp being a chat (due to a restriction, I'm using Struts 1). In this JSP, I have the following div :

<div class="conteudo" id="conteudo" name="conteudo"> .

I need to return an automatic response (can be anything) from the server whenever the user sends something to the chat page, which I can not do. However, I have the script to display the user messages on the screen, and it works. The script is as follows:

<script src="inc/jquery.js"></script>
    <script>
    $(document).ready(function(){
            $("#enviar").click(function(){
                var mensagem = $("#texto").val();
                mensagem = mensagem.replace(/\r?\n/g, '<br />');
                var cliente = "Cliente "+":";
                var hora = (new Date).getHours();
                var min = (new Date).getMinutes();
                if(min <10)
                    min = "0"+min;
                var sec = (new Date).getSeconds();
                if(sec <10)
                    sec = "0"+sec;
                var horario = hora+":"+min+":"+sec;

                $("#conteudo").append($("<div[...]{AQUI SE INSERE A MENSAGEM, E ELA FUNCIONA.}[...]</div>"));

            });
    });
</script>

Is there anything I can do to give a kind of append too? Remember that I need a message to be inserted in the chat after someone types something.

    
asked by anonymous 18.11.2014 / 20:02

1 answer

1

A simple way would be to use AJAX polling. Something like this:

function alguemDigitandoAlgo(dados) {
  // ... Aqui é com você.
}

(function pollServerForNewMessage() {
  $.getJSON('/alguem_digitando_algo.jsp', function(response) {
    if (response.newMessage) {
      alguemDigitandoAlgo(response.message);
    }
    setTimeout(pollServerForNewMessage, 1000);
  });
}());

Other top alternatives would be to use comet or websockets, but AJAX is the simplest way.

In addition, you still have to handle cases where the connection fails, crashes, etc.

Here the source where I adapted the code.

    
18.11.2014 / 21:43