javascript - 未使用 Ajax 将 PHP 记录插入数据库
问题描述
这是 AJAX 请求正文
阿贾克斯
var date = new Date().toLocaleTimeString();
var text=this.value;
var id=1;
$.ajax({
type: "GET",
url: "StoreMessages.php" ,
data: { room: id, msg:text,sendat:date }
});
PHP 代码
if(isset($_GET['room']))
{
$chatroom_name = $_GET['room'];
if(isset($_GET['msg']))
{
$text= $_GET['msg'] ;
if(isset($_GET['sendat']))
{
$local_time= $_GET['sendat']);
insertMessage( $text,$local_time, $chatroom_name);
}
}
}
function insertMessage($message_body,$local_time,$room_id)
{
echo "<script type='text/javascript'>alert('$message_body');</script>";
echo "<script type='text/javascript'>alert('$local_time');</script>";
echo "<script type='text/javascript'>alert('$room_id');</script>";
$conn = new mysqli($GLOBALS['server'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db_name']);
if($conn==false)
{
die("unable to connect database");
}
$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES ('$message_body', '$local_time', '$room_id')";
if(mysqli_query($conn,$sql)){
echo "record inserted successfully"."<br/>";
}
else{
echo "error".mysqli_error($db_conn);
}
解释
当用户键入消息并按回车键时,ajax 调用触发对于其他变量,我正在尝试将实时聊天存储到数据库
解决方案
调试的第一步是/正在诊断故障发生的位置。去做这个:
- 打开你的开发者控制台
- 转到
network
选项卡 - 进行任何触发 AJAX 请求的操作
network
单击选项卡中显示的请求- 转到
response
选项卡*
*如果请求的状态代码是 500,这也表明脚本在 PHP 端失败。转到服务器并查看错误日志。
从我们在response
选项卡中得到的响应中,我们确定问题是这一行的尾括号:
$local_time= $_GET['sendat']);
此外,您应该使用参数化查询。任何字段中的单引号都会中断您的查询。
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
大致:
$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES (?, ?, ?)";
然后prepare
是bind
值和execute
查询。
另外我会发回一个 JSON 对象而不是 JS 代码。看看http://php.net/manual/en/function.json-encode.php。
推荐阅读
- android - 如果您是内部测试人员,如何在 google play 上找到应用程序
- python - Django - 日志记录 - 在其中运行函数 GET 时如何获取类名?
- javascript - 完成填字游戏后如何显示弹出窗口消息 - JS
- linux - flutter:Gradle build daemon 意外消失(可能已被杀死或崩溃)
- visual-studio-code - 如何为 vscode 选择正确的扩展版本?
- git - Github Pages 服务于 `README.md`,尽管它是从 `\docs` 构建的
- css - 为什么调整窗口大小时flexbox向左移动
- angular - 由于结构角度,无法路由到另一个页面
- javascript - 如何在以下代码中添加数字?
- javascript - 在引导程序中对齐垂直中心 CSS 时钟