javascript - 无法在聊天应用程序中使用 Ajax 调用从控制器返回 html
问题描述
所以我正在 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")
}
});
}
这是我的控制器
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;
}
视图的简单版本和我想在其中插入数据的 div:
<div id="chathistory"></div>
请注意,模型编写正确(我确实对其进行了测试),并且调用编写正确,因为每当我删除 foreach 循环并将其添加到我的控制器时:
echo json_encode($history);
然后控制台在我的 ajax 调用中记录数据,我可以毫无问题地获得完整的聊天记录。所以我的猜测是 foreach 循环和 html 渲染有问题!
另外:我确实在 github 上查看了一些简单的网络应用程序聊天,他们确实以相同的方式编写了控制器,并且对他们来说非常好用。那请问你觉得是什么问题?
解决方案
dataType : "json"
告诉 jQuery 在响应中期待 JSON,但您正在从控制器返回 HTML。因此,当它尝试将您的 HTML 解析为 JSON 时,它可能会抛出错误。删除该行,或指定
dataType: "html"
反而
推荐阅读
- node.js - Ng new 安装 Angular 8 项目而不是 9
- python - Python - 如何遍历 sql server 查询的输出并将输出的每一行保存为 rtf 文件
- amazon-web-services - 是否有在事件“CreateBucket”中使用的变量指代新存储桶的名称?
- python-3.x - 如何使用 python + requests 获取 instagram sessionid
- python - cmath 和 numpy 都给出了 asin(10) 的“不正确”值
- ruby-on-rails - 如果条件,Rails模型验证字段的值
- java - Springboot 2.1 Actuator /info 将构建和 git 时间显示为时间戳
- php - 我们有一个用户在 m/d/Y 中输入日期,我正试图将它输入 Y/m/d 以保存到 MYSQL
- c++ - 创建一个按位或(fetch_or)锁定的互斥锁?
- java - SQLlite 数据库在 android studio 4 中无法正常工作