XMLHttpRequest PHP聊天

时间:2017-08-27 14:00:40

标签: javascript php jquery json ajax

我正在尝试创建一个系统,以在同一页面上的2个或多个单独的聊天(在数据库中存储不同的消息)上显示消息。每个聊天都有id来区分它们,我创建了一个函数来浏览每个正在使用的聊天并为它们打印approprite消息,但只有1个聊天获取消息。 代码: HTML

<div class="full_wrap">
   <div class="force-overflow"></div>
   <div id="Sidenav" class="side">

      <h2>Chat Settings & Info</h2>

      <a id="closebtn" href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>

      <div class="authr">

         <a>
            <div class="authr_img"></div>​
         </a>

         <form action="mypage.php" method="post">
            <div class="authr_name">
               <button value="<?php echo $chat_authr ?>" name="userlink" class="subm_as_text"><?php echo $chat_authr;  ?></button>
            </div>
         </form>
      </div>

      <div class="chat_info">

         <div class="chat_descy">

            <h2>Chat Description</h2>
            <div class="descc">
               <h3><?php echo $chat_description; ?></h3>
            </div>
         </div>

         <div class="chat_fol"><h2>Chat users: <?php echo $num_users; ?></h2></div>

         <div class="chat_back">
            <h2> Change Chat Wallpaper</h2>

            <form method="post" action="picture.php" enctype="multipart/form-data">
               <input type="file" id="upload" class="custom-file-input" name="chat_wall">
               <input type="submit" class="chat_wall_subm" value="Change"/>
            </form>
         </div>
      </div>

      <form method="post" action="chat.php" >
         <!--<input type="submit" class="chat_leave" name="" value="Leave Chat">-->

         <button class="chat_leave" name="chat_leave" value="<?php echo $chat_index; ?>" >Leave Chat</button>
      </form>
   </div>


   <div class="mnav">
      <span onclick="openNav()">&#9776;</span>
      <i class="material-icons" id="chat_un_small" onclick="chat_un_small()">arrow_upward</i>
      <h1><?php echo $chat_title ?></h1>

   </div>


   <!--one ting-->
   <div class="conceal_wrapper">
      <div class="msgs" id="5e2dbe2be3b5927c588509edb1c46f7d">
      </div>

      <form method="post" id="form_5e2dbe2be3b5927c588509edb1c46f7d" class="comform">
         <div class="wcom" >
            <input maxlength="140" type = "text" id="5e2dbe2be3b5927c588509edb1c46f7d"  class="comin" placeholder="My message..." name="sendmsg" autocapitalize="off" autocorrect="off"/>
            <input class="hidden_index" type="text" value="5e2dbe2be3b5927c588509edb1c46f7d" name="chat_index"/>
         </div>
      </form>
   </div>

   <div class="chat_enlarge">
      <div class="chat_enlarge_full" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_full()"></div>
      <div class="chat_enlarge_standard"  onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_standard()"></div>
      <div class="chat_enlarge_small"  onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_small()"></div>
   </div>

</div>



<div class="full_wrap">
   <div class="force-overflow"></div>
   <div id="Sidenav" class="side">

      <h2>Chat Settings & Info</h2>

      <a id="closebtn" href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>

      <div class="authr">

         <a>
            <div class="authr_img"></div>​
         </a>

         <form action="mypage.php" method="post">
            <div class="authr_name">
               <button value="<?php echo $chat_authr ?>" name="userlink" class="subm_as_text"><?php echo $chat_authr;  ?></button>
            </div>
         </form>

      </div>


      <div class="chat_info">
         <div class="chat_descy">
            <h2>Chat Description</h2>
            <div class="descc">
               <h3><?php echo $chat_description; ?></h3>
            </div>
         </div>

         <div class="chat_fol"><h2>Chat users: <?php echo $num_users; ?></h2></div>

         <div class="chat_back">
            <h2> Change Chat Wallpaper</h2>

            <form method="post" action="picture.php" enctype="multipart/form-data">
               <input type="file" id="upload" class="custom-file-input" name="chat_wall">
               <input type="submit" class="chat_wall_subm" value="Change"/>
            </form>
         </div>

      </div>

      <form method="post" action="chat.php" >
         <!--<input type="submit" class="chat_leave" name="" value="Leave Chat">-->

         <button class="chat_leave" name="chat_leave" value="<?php echo $chat_index; ?>" >Leave Chat</button>
      </form>
   </div>


   <div class="mnav">
      <span onclick="openNav()">&#9776;</span>
      <i class="material-icons" id="chat_un_small" onclick="chat_un_small()">arrow_upward</i>
      <h1><?php echo $chat_title ?></h1>

   </div>


   <!--one ting-->
   <div class="conceal_wrapper">
      <div class="msgs" id="9503e253936e716f18d9c57b4f97d618">


      </div>



      <form method="post" id="form_9503e253936e716f18d9c57b4f97d618" class="comform">
         <div class="wcom" >
            <input maxlength="140" type = "text" id="9503e253936e716f18d9c57b4f97d618"  class="comin" placeholder="My message..." name="sendmsg" autocapitalize="off" autocorrect="off"/>
            <input class="hidden_index" type="text" value="9503e253936e716f18d9c57b4f97d618" name="chat_index"/>
         </div>
      </form>
   </div>

   <div class="chat_enlarge">
      <div class="chat_enlarge_full" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_full()"></div>
      <div class="chat_enlarge_standard"  onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_standard()"></div>
      <div class="chat_enlarge_small"  onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_small()"></div>
   </div>

</div>

因此有两个由full_wrap类分隔的聊天。 msgs具有不同的id,用于为db

中的每个聊天存储唯一的聊天索引

Javascript:

$( document ).ready(function() {
  chat_receivemsgs();
});


function chat_receivemsgs(){
  var cusid_ele = document.getElementsByClassName('msgs');
  if(cusid_ele.length == 0) {
    console.log("hi");
  } else {
    for (var i = 0; i < cusid_ele.length; ++i) {
      var item = cusid_ele[i];
      var item_id = item.id;
      console.log(cusid_ele.length);

      for (var i = 0; i < cusid_ele.length; ++i) {
        var item = cusid_ele[i];
        var item_id = item.id;
        console.log(item_id);

        var xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            console.log("yes");
            console.log(item_id);
            //  document.getElementById(item_id).innerHTML = this.responseText;
            $("#"+item_id).html(this.responseText);
          }else{
            console.log("no");
            console.log(item_id);
          }
        }
        xmlhttp.open("GET","receivemsg.php?q="+item_id,true);
        xmlhttp.send();
      }
    }
  }
}

receivemsgs.php只选择messages表中由index_id给出的索引索引的所有消息。问题是如上所述只有与9503e253936e716f18d9c57b4f97d618 id的聊天才会收到消息。

我听说请求重复了4次,但我不是这个领域的专家。通过使用控制台,我知道它忽略了第一次聊天,只生成了9503e253936e716f18d9c57b4f97d618的消息。

任何帮助都会很感激。 此外,如果有更好的方法来控制同一页面上的多个聊天,我会很高兴知道如何。 谢谢你的时间。

1 个答案:

答案 0 :(得分:0)

问题在于你如何使用XMLHttpRequest。

请参阅此代码段:

function Obj() {
}

Obj.prototype = {
	callFunc: function() {
		setTimeout(this.func, 1000);
	}
};


function test() {
	var ids = ['id1', 'id2'];

	for (var i = 0 ; i < 2 ; ++i) {
		var id = ids[i];
		var obj = new Obj();

		obj.func = function() {
			console.log(id);
		};

		obj.callFunc();
	}
}

test();

如您所见,代码两次向控制台输出“id2”。这与你的问题类似。

obj.func中(在您的代码中,xmlhttp.onreadystatechange),id变量(分别为item_id)来自外部函数。分配obj.func时的值不会“保存”。当函数最终执行时,它将使用该变量的最后一个已知值。

所以这就是发生的事情:

  • i = 0
  • id = ids[0] = 'id1'
  • 创建了一个新的Obj(让我们称之为obj1)并分配给obj
  • obj1.func已创建
  • obj1.callFunc被调用,程序obj1.func稍后将被调用
  • i = 1
  • id = ids[1] = 'id2'
  • 创建了一个新的Obj(让我们称之为obj2)并分配给obj
  • obj2.func已创建
  • obj2.callFunc被调用,程序obj2.func稍后将被调用
  • obj1.func被调用,它会打印id的最后一个值,即“id2”
  • obj2.func被调用,它会打印id的最后一个值,即“id2”

围绕这种行为有几种方法。您可以以某种方式从PHP的输出中检索item_id。您可以将item_id设置为xmlhttp的成员并在您的函数中使用该成员(xmlhttp.item_id = item_id;然后在函数this.item_id内)。或者您可以使用bind。使用后一种解决方案,您的代码将变为:

xmlhttp.onreadystatechange = function(this_item_id) {
  if (this.readyState == 4 && this.status == 200) {
    console.log("yes");
    console.log(this_item_id);
    //  document.getElementById(this_item_id).innerHTML = this.responseText;
    $("#"+this_item_id).html(this.responseText);
  }else{
    console.log("no");
    console.log(this_item_id);
  }
}.bind(xmlhttp, item_id);

xmlhttp.open("GET","receivemsg.php?q="+item_id,true);
xmlhttp.send();

顺便说一下,我不明白为什么你在cusid_ele上迭代两次(你有两个嵌套循环)。