Events and changes in a JSP?

Asked

Viewed 88 times

1

Hello. I have a jsp being a chat (due to a restriction, I am 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 am not able to do. However, I have the script to display user messages on the screen, and it works. The Script is the following:

<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>

There’s nothing I can do to give a kind of append also? Remembering that I need any message to be inserted into the chat after someone has typed something.

1 answer

1

A simple way would be to use an AJAX Poster. 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 superior alternatives would be to use Comet or websockets, but AJAX is the simplest way.

Also, you still have to deal with cases where the connection fails, falls, etc.

Here to source where I adapted the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.