script.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. function jsonPost(url, data) {
  2. return new Promise((resolve, reject) => {
  3. var x = new XMLHttpRequest();
  4. x.onerror = () => reject(new Error('jsonPost failed'))
  5. x.open("POST", url, true);
  6. x.send(JSON.stringify(data))
  7. x.onreadystatechange = () => {
  8. if (x.readyState == XMLHttpRequest.DONE && x.status == 200){
  9. resolve(JSON.parse(x.responseText))
  10. }
  11. else if (x.status != 200){
  12. reject(new Error('status is not 200'))
  13. }
  14. }
  15. })
  16. }
  17. let inp1 = document.querySelector('.user-name'),
  18. inp2 = document.querySelector('.user-massege'),
  19. butn = document.querySelector('.send-massege'),
  20. chat = document.querySelector('.chat');
  21. function sayComrad(){
  22. function checkerson(){
  23. inp1.value == '' || inp2.value == ''? butn.classList.add('block-btn'): butn.classList.remove('block-btn');
  24. }
  25. inp1.oninput=inp2.oninput=checkerson;
  26. butn.onclick = () => {
  27. (inp1.value == '' || inp2.value == '') ? reject() : resolve();
  28. function resolve(){
  29. jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: inp1.value, message: inp2.value});
  30. inp1.value = '';
  31. inp2.value = '';
  32. }
  33. function reject() {
  34. butn.classList.add('block-btn');
  35. }
  36. }
  37. }
  38. sayComrad()
  39. let smsNamb = 0
  40. function getChatData() {
  41. jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: smsNamb})
  42. .then((d) => createSpaceForChat(d));
  43. }
  44. getChatData()
  45. function createSpaceForChat(data) {
  46. console.log(smsNamb)
  47. for (let details of data.data){
  48. if (details.nick === '' || details.massage === '' || typeof(details.nick) === 'object' || typeof(details.nick) === 'undefined') {
  49. continue;
  50. };
  51. let main = document.createElement('div');
  52. let iner = document.createElement('div');
  53. main.appendChild(iner);
  54. let timeSend = document.createElement('time');
  55. let ttiimmee = new Date(details.timestamp);
  56. timeSend.innerText = ((ttiimmee.getHours()+'').length>1 ? ttiimmee.getHours() : '0'+ttiimmee.getHours()) +':'+ ((ttiimmee.getMinutes()+'').length>1 ? ttiimmee.getMinutes() : '0'+ttiimmee.getMinutes());
  57. main.appendChild(timeSend);
  58. let userName = document.createElement('b');
  59. userName.innerText = details.nick + ':';
  60. iner.appendChild(userName);
  61. let message = document.createElement('time');
  62. message.innerText = details.message;
  63. iner.appendChild(message);
  64. chat.prepend(main)
  65. }
  66. smsNumb = data.nextMessageId;
  67. update();
  68. }
  69. function update(){
  70. setInterval(getChatData(),100)
  71. }