我正在为学校作业创建一种社交媒体平台。我创建了一个简单的聊天工具。每个朋友关系都有一个对话。
问题是,当我使用Ajax重新加载所有聊天消息时,我无法使用$_GET
方法获取我保存在url中的对话ID。没有这个ID我不能使用我的Chat
类中的功能。 如果一些代码是用荷兰语编写的,我很抱歉。
该网址看起来像这样chat.php?gesprek_id=1
。 Gesprek
或Conversation
编号就像我说的保存在网址中。 Ajax请求后,我接到通知:
'的通知:未定义指数:gesprek_id在......'
它指的是在PHP $ _GET方法。
我的代码:
聊天类:
public function getNewMessages($gesprekId){
$conn = Db::getInstance();
$stm = $conn->prepare("SELECT * from chat WHERE gesprek_id = :gesprek_id AND tijd > :tijd");
$stm->bindValue(":gesprek_id", $gesprekId, PDO::PARAM_STR);
$stm->bindValue(":tijd", $_SERVER['REQUEST_TIME'], PDO::PARAM_STR);
$stm->execute();
$res = $stm->fetchAll();
return $res;
}
腓阿贾克斯
<?php
header('Content-Type: application/json');
include_once('../classes/Db.php');
include_once('../classes/Chat.php');
session_start();
$gesprekId = $_GET['gesprek_id'];
$chat = new \Kvm\Chat();
$newMessages = $chat->getNewMessages($gesprekId);
?>
<?php foreach ($newMessages as $message): ?>
<?php $profile = $chat->getUserMessage($message['user_id']); ?>
<?php if ($message['user_id'] == $_SESSION['user_id']): ?>
<div id="messageBlock" class="blockRed">
<div class="profile-chat">
<img class="profileSmall" src="<?php echo $profile['avatar']; ?>"/>
<div>
<h4 class="username"><?php echo $profile['firstname'] . ' ' . $profile['lastname']; ?></h4>
</div>
</div>
<p class="message"><?php echo $message['message'] ?></p>
</div>
<?php else: ?>
<div id="messageBlock" class="blockYellow">
<div class="profile-chat">
<img class="profileSmall src="<?php echo $profile['avatar']; ?>"/>
<div>
<h4 class="username"><?php echo $profile['firstname'] . ' ' . $profile['lastname']; ?></h4>
</div>
</div>
<p class="message"><?php echo $message['message'] ?></p>
</div>
<?php endif; ?>
<?php endforeach; ?>
编辑在阿贾克斯(添加了几行找到正确的 'gesprek_id' 用的解决方案$ _GET问题) Ajax/Jquery:
$(document).ready(function() {
function loadchat() {
var messageList = $('#allMessages');
var gesprekId = $('.message').attr('data-gesprekId');
$(messageList).load('ajax/newChat.php?gesprek_id='+gesprekId);
}
setInterval(loadchat, 50000);
loadchat();
});
我希望我的问题很清楚。
这也是我在Stackoverflow问的第一个问题,所以我很抱歉如果有什么不好描述。 (并且对不起,如果我在英文中犯了一些错误;)) 先谢谢你。
您在请求脚本时没有设置GET参数,它应该是这样的:'$(messageList).load('ajax/newChat.php?gesprek_id = xxx');'您可以检查它是否被设置'=>'if(isset($ _ GET ['gesprek_id'])){...} else {other logic insert here}'。 PS:'session_start()'应该是你的文件的第一行(更多:https://stackoverflow.com/questions/10542089/when-to-use-session-start) –
“该网址看起来像这样的聊天。 PHP的?gesprek_id = 1'“ - 根据你向我们展示的AJAX代码,URL是:''ajax/newChat.php'' – David
我明白了,我尝试了这种方法,它几乎可以工作!div重载所有但在间隔期结束后,这个div又是空的,'gesprek_id'是未定义的,几秒钟后,div再次充满了我的所有消息等。 –