使用XMLHttpRequest从函数调用时,函数按预期工作,但是使用EventSource从函数调用时,函数失败。为什么是这样?

时间:2019-02-12 21:20:06

标签: javascript chat

我找不到解决我问题的类似问题。我正在使用Javascript创建基本的Messenger。我在一个名为loadMessage,messageListener和displayMessage的单独js文件中具有三个函数。

函数loadMessage调用所有现有消息的数据库,然后调用displayMessages构造一些div,这些div用于显示从服务器获取的消息。这些div被创建为彼此下方,底部的div是新创建的div,显示最新消息。

所有消息创建完毕后,loadMessage然后调用messageListener。此功能“监听”数据库中可能出现的任何新消息。如果出现,则messageListener调用displayMessage。我希望这会像以前一样在其他div的底部创建一个新的div,但是当它调用displayMessage时,其行为与loadMessage调用displayMessage时的行为完全不同。

具体来说,它不会创建新的div,而只是更改现有div中的文本,该文本出现在新创建的div中的任何位置(例如,显示第一条消息或在中间某处显示一个消息的div)。

我的html和PHP文件的行为均符合预期,因此我认为这是这三个函数中的问题。

如何解决此问题以达到预期效果?先谢谢了!

代码:

 // Loads chat messages history and listens for upcoming ones.
function loadMessages(userID, contactID) {
    contactIDGlobal = contactID;
    //load existing messages
    var today = new Date();
    var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
    var param = "userID="+userID+"&contactID="+contactID+"&date="+date;

    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","Interface-getMessage.php?", true);
    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xmlhttp.send(param);
    xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    //retrives a string of all past messages
    var messageString = xmlhttp.responseText;
    //parse string to get messages. 
    var parseMessageString = messageString.split('-');
    for (var i = 0; parseMessageString[i] !== null && parseMessageString[i] !== ''; i = i+5){
      var contactID = parseMessageString[i];
      var senderID = parseMessageString[i+1];
      var message = parseMessageString[i+2];
      var time = parseMessageString[i+3];
      var mID = parseMessageString[i+4];
      displayMessage(userID, senderID, contactID, message, date, time, mID);
    }
  }
};
//listen for new messages
    messageListener(userID, contactID);   
}


function messageListener(userID, contactID){
    if(typeof(EventSource)!=="underfined") {
        var newMessage = new EventSource("testerfile.php?userID="+userID+"&contactID="+contactID);
        newMessage.onmessage = function(event) {
          var newMessageData = event.data;
          var parseNewMessage = newMessageData.split('-');
          //sender ID may be different to the userID due to the way that messages are stored on the server. Received messages have a different sender.
          var senderID = parseNewMessage[0];
          var contactID = parseNewMessage[1];
          var message = parseNewMessage[2];
          var date = parseNewMessage[3];
          var time = parseNewMessage[4];
          var messageID = parseNewMessage[5];

          console.log(event.data);
          displayMessage(userID, senderID, contactID, message, date, time, messageID);      
        };
    }else {
        document.getElementById("messages").innerHTML = "Your browser does not support this";
    } 

    }

// Displays a Message in the UI.
function displayMessage(userID, senderID, contactID, nMessage, date, time, id){
  var messageListElement = document.getElementById('messages');
  var messageInputElement = document.getElementById('message');
  // If an element for this message already exists, then get it
  var id = id;
  var div = document.getElementById(id);
  // If an element for that message does not exists yet we create it.
  if (!div) {
    var container = document.createElement('div');
    if (userID == senderID){
      container.innerHTML = SENDER_MESSAGE_TEMPLATE;
    }else{
      container.innerHTML = MESSAGE_TEMPLATE;
      }
    div = container.firstChild;
    div.setAttribute('id', id);
    for (var i = 0; i < messageListElement.children.length; i++) {
      var child = messageListElement.children[i];
    }
    messageListElement.insertBefore(div, child);
  }
  var messageElement = div.querySelector('.message');
  messageElement.textContent = nMessage;
  // Replace all line breaks by <br>.
  messageElement.innerHTML = messageElement.innerHTML.replace(/\n/g, '<br>');
}


// Template for messages.
var SENDER_MESSAGE_TEMPLATE =
    '<div class="sender_message-container">' +
      '<div class="message"></div>' +
    '</div>';

var MESSAGE_TEMPLATE =
    '<div class="message-container">' +
      '<div class="message"></div>' +
    '</div>';

1 个答案:

答案 0 :(得分:0)

问题出在返回的日期是y-m-d,而解析器使用“-”。这意味着我正在创建一个时间变量,该时间变量是我的日期的月份,而消息ID是一天。我进行了以下更改以解决此问题...

  var newMessageData = event.data;
  var parseNewMessage = newMessageData.split('-');
  //sender ID may be different to the userID due to the way that messages are stored on the server. Received messages have a different sender.
  var senderID = parseNewMessage[0];
  var contactID = parseNewMessage[1];
  var message = parseNewMessage[2];
  var date = parseNewMessage[3]+"-"+parseNewMessage[4]+"-"+parseNewMessage[5];
  var time = parseNewMessage[6];
  var messageID = parseNewMessage[7];