example_chat.html 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <html>
  2. <head>
  3. <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
  4. </head>
  5. <body>
  6. <input id="msg" type="text">
  7. <button id="send">Send</button>
  8. <div id="logs">
  9. </div>
  10. <script>
  11. $(document).ready(function(){
  12. $("#send").click(function(){
  13. var msg = $("#msg").val();
  14. console.log(msg);
  15. if (msg.length > 0)
  16. $.post("/send", msg);
  17. $("#msg").val("");
  18. });
  19. $("#msg").keyup(function(event){
  20. if(event.keyCode == 13){
  21. $("#send").click();
  22. }
  23. });
  24. var lastLog = 0;
  25. var updateLog;
  26. updateLog = function(data)
  27. {
  28. console.log("recv ");
  29. console.log(data);
  30. var lastLog = data.last*1;
  31. console.log("lastLog: " + lastLog);
  32. var s = "";
  33. function htmlEncode(s)
  34. {
  35. return s.replace(/&(?!\w+([;\s]|$))/g, "&amp;")
  36. .replace(/</g, "&lt;").replace(/>/g, "&gt;");
  37. }
  38. for(var x in data.msgs)
  39. {
  40. s = htmlEncode(data.msgs[x]) + "<BR>" + s;
  41. }
  42. $("#logs").html(s+$("#logs").html());
  43. var failFunction;
  44. failFunction = function(){
  45. $.getJSON("/logs/"+lastLog, updateLog).fail(failFunction);
  46. };
  47. $.getJSON("/logs/"+lastLog, updateLog).fail(failFunction);
  48. }
  49. $.getJSON("/logs", updateLog);
  50. });
  51. </script>
  52. </body>
  53. </html>