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

问题描述 投票:0回答:1

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

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

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

具体来说,它不会创建一个新的div,而只是更改现有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>';
javascript chat
1个回答
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];
热门问题
推荐问题
最新问题