csapp.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. function g(i) { return document.getElementById(i) };
  2. var xhttp, updateTime, reqTime, reqFin;
  3. var msgList = document.getElementById('msgs');
  4. g('cmdInput').addEventListener("keyup", function(event) {
  5. event.preventDefault();
  6. if (event.keyCode === 13) {
  7. sendCmd();
  8. }
  9. });
  10. function sendCmd() {
  11. var form = g('cmdForm');
  12. msgList.innerHTML += 'Sent: ' + g('cmdInput').value + '\n';
  13. g('cmd').value=g('cmdInput').value;
  14. g('cmdInput').value='';
  15. g('cmdInput').value = '';
  16. msgList.scrollTop = msgList.scrollHeight;
  17. return transmit(form);
  18. }
  19. var lastMsgIndex=0;
  20. function transmit(f) {
  21. if (!xhttp) {
  22. reqTime = 0;
  23. reqFin = false;
  24. xhttp = new XMLHttpRequest();
  25. xhttp.timeout = 1000;
  26. xhttp.overrideMimeType("text/plain");
  27. xhttp.open('POST', 'webcsapi');
  28. xhttp.send(f ? (new FormData(f)) : '');
  29. xhttp.onreadystatechange = function () {
  30. if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
  31. var data = xhttp.responseText.split("\n");
  32. for(i=0; i < data.length; i++) {
  33. var numEnd = data[i].indexOf("}");
  34. var num = parseInt(data[i].substring(1, numEnd));
  35. var msg = data[i].substring(numEnd+1);
  36. if(num > lastMsgIndex || lastMsgIndex == 0) {
  37. msgList.innerHTML += msg;
  38. msgList.scrollTop = msgList.scrollHeight;
  39. lastMsgIndex = num;
  40. }
  41. }
  42. xhttp = null;
  43. updateTime = 0;
  44. reqFin = true;
  45. }
  46. else {
  47. if(!reqFin && reqTime > 10) {
  48. xhttp = null;
  49. reqFin = true;
  50. }
  51. }
  52. }
  53. }
  54. return false;
  55. }
  56. transmit();
  57. setInterval(transmit, 2000);