gpt4 book ai didi

javascript - 无法在聊天应用程序中使用 Ajax 调用从 Controller 返回 html

转载 作者:行者123 更新时间:2023-12-02 20:55:10 25 4
gpt4 key购买 nike

所以我正在 CRM 中构建一个集成的聊天应用程序。每当登录的用户单击某个联系人时,它就会使用 Ajax 调用显示两个用户之间的聊天历史记录,这就是麻烦开始的地方。

这是我的 Ajax 调用代码:

function GetChatHistory(receiver_id){
$.ajax({
dataType : "json",
url: '/chat/get_chat_history_by_user',
data:{receiver_id:receiver_id},
success:function(data)
{

$('#chathistory').html(data);
ScrollDown();
},
error: function (jqXHR, status, err) {
// alert('Local error callback');
alert("error fetching")
}
});
}

这是我的 Controller

public function get_chat_history_by_user(){
//get the receiver id
$receiver_id = $this->input->get('receiver_id');
//get the sender id
$Logged_sender_id = $this->session->userdata['user_id'];

$history = $this->chat_model->GetReciverChatHistory($receiver_id);

foreach($history as $chat):

$message_id = $chat['id'];
$sender_id = $chat['sender_id'];
$userName = $this->UserModel->GetName($chat['sender_id']);
$userPic = $this->UserModel->PictureUrlById($chat['sender_id']);

$messagebody = $chat['message'];
$messagedatetime = date('d M H:i A',strtotime($chat['message_date_time']));
?>
<?php if($Logged_sender_id!=$sender_id){?>
<!-- Message. Default to the left -->
<div class="direct-chat-msg">
<div class="direct-chat-info clearfix">
<span ><?=$userName;?></span>
<span ><?=$messagedatetime;?></span>
</div>
<!-- /.direct-chat-info -->

<div class="direct-chat-text">
<?=$messageBody;?>
</div>
<!-- /.direct-chat-text -->

</div>
<!-- /.direct-chat-msg -->
<?php }else{?>
<!-- Message to the right -->
<div class="direct-chat-msg right">
<div class="direct-chat-info clearfix">
<span ><?=$userName;?></span>
<span ><?=$messagedatetime;?></span>
</div>
<!-- /.direct-chat-info -->

<div class="direct-chat-text">
<?=$messageBody;?>
</div>
<!-- /.direct-chat-text -->
</div>
<!-- /.direct-chat-msg -->
<?php }?>

<?php
endforeach;
}

简单版本的 View 和我想在其中插入数据的 div :

<div id="chathistory"></div>

请注意,模型编写正确(我确实测试了它们),并且调用编写正确,因为每当我删除 foreach 循环并将其添加到我的 Controller 时:

echo json_encode($history);

然后控制台在我的ajax调用中记录数据,我可以毫无问题地获得完整的聊天历史记录。所以我的猜测是 foreach 循环和 html 渲染有问题!

另外:我确实在 github 上查看了一些简单的网络应用程序聊天,他们确实以相同的方式编写了 Controller ,并且它对他们来说工作得非常好。那么您认为问题出在哪里?

最佳答案

dataType : "json" 

告诉 jQuery 在响应中期待 JSON,但您正在从 Controller 返回 HTML。因此,当它尝试将 HTML 解析为 JSON 时,它可能会抛出错误。删除该行,或指定

dataType: "html" 

相反

关于javascript - 无法在聊天应用程序中使用 Ajax 调用从 Controller 返回 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61506002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com