javascript - 将数据插入数据库后无法从 API 获取值
问题描述
我为 Web 留言板应用程序创建了一个 api。当我点击提交时,数据被插入到数据库中,然后在页面中显示结果列表。为什么我无法在页面上获取创建时间?如果我想获得创建时间,我必须按重新加载页面,创建时间会显示在页面上。API有什么部分需要修改吗?谢谢!
const siteKey = 'oscar';
const loadMorebtn = "<button class='load_btn btn'>Load More</button>";
const msgSection = $('.msg_section');
let lastId = null;
let isEnd = false;
function encodeHTML(input) {
return input.replace(/\&/g, '&')
.replace(/\</g, '<')
.replace(/\>/g, '>')
.replace(/\"/g, '"')
.replace(/\'/g, ''')
.replace(/\//g, '/')
}
function appendMsgToDOM(container, msg, isPrepend) {
const htmlContent = `
<div class="card mt-4">
<div class="card-body d-flex flex-column">
<h5 class="card-title">${encodeHTML(msg.nickname)}</h5>
<p class="card-text">${encodeHTML(msg.content)}</p>
<p class="card_created_time align-self-end">${msg.created_at}</p>
</div>
</div>
`
if (isPrepend) {
container.prepend(htmlContent);
} else {
container.append(htmlContent);
}
}
// Only for get message
function getMsgsAPI(siteKey, before, cb) {
let url = `http://localhost/w12/hw1/api_message.php?site_key=${siteKey}`;
if (before) {
url += '&before=' + before
}
$.ajax({
url,
}).done((data) => {
cb(data);
})
}
function getMsgs() {
$('.load_btn').hide();
if (isEnd) return;
getMsgsAPI(siteKey, lastId, (data) => {
if (!data.result) {
alert(data.message);
return;
}
const messages = data.messages;
for (let msg of messages) {
appendMsgToDOM(msgSection, msg)
}
if (messages.length === 0) {
isEnd = true
} else {
lastId = messages[messages.length - 1].id;
msgSection.append(loadMorebtn)
}
})
}
$(document).ready(() => {
getMsgs();
msgSection.on('click', '.load_btn', () => {
getMsgs();
})
$('.add_msg_form').submit((e) => {
e.preventDefault();
const newMsgData = {
'site_key': 'Oscar',
'nickname': $('input[name=nickname]').val(),
'content': $('textarea[name=content]').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost/w12/hw1/api_add_message.php',
data: newMsgData
}).done(function (data) {
if (!data.result) {
alert(data.message);
return;
}
$('input[name=nickname]').val('');
$('textarea[name=content]').val('');
appendMsgToDOM(msgSection, newMsgData, true);
})
});
})
用于显示数据的 API
<?php
require_once('./conn.php');
// Make sure the format of response is json
header('Content-type:application/json;charset=utf-8');
// CORS
header('Access-Control-Allow-Origin: *');
if(empty($_GET['site_key'])) {
$json = array(
'result'=>false,
'message'=>'Please input the site_key in URL'
);
// covert the response to json format
$response = json_encode($json);
echo $response;
die();
}
$site_key = $_GET['site_key'];
$sql = "SELECT * FROM oscar_msgboard WHERE site_key = ? " .
(empty($_GET['before'])? '':'and id < ?') .
" ORDER BY id DESC LIMIT 5";
$stmt = $conn->prepare($sql);
if(empty($_GET['before'])) {
$stmt->bind_param('s', $site_key);
} else {
$stmt->bind_param('si', $site_key, $_GET['before']);
}
$result = $stmt->execute();
if(!$result) {
$json = array(
'result'=>false,
'message'=>'fail to connect to the server'
);
// covert the response to json format
$response = json_encode($json);
echo $response;
die();
}
$result = $stmt->get_result();
$messages = array();
while($row = $result->fetch_assoc()) {
array_push($messages, array(
'id'=>$row['id'],
'nickname'=>$row['nickname'],
'content'=>$row['content'],
'created_at'=>$row['created_at']
));
}
$json = array(
'result'=>true,
'messages'=>$messages
);
$response = json_encode($json);
echo $response;
?>
插入数据的API
<?php
require_once('./conn.php');
// Make sure the representation of response is json
header('Content-type:application/json;charset=utf-8');
header('Access-Control-Allow-Origin: *');
if(empty($_POST['nickname'])|| empty($_POST['site_key']) || empty($_POST['content'])) {
$json = array(
'result'=>false,
'message'=>'Please input a message'
);
// covert the response to json format
$response = json_encode($json);
echo $response;
die();
}
$nickname = $_POST['nickname'];
$site_key = $_POST['site_key'];
$content = $_POST['content'];
$sql = "INSERT into oscar_msgboard (site_key, nickname, content) values (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sss', $site_key, $nickname, $content);
$result = $stmt->execute();
if(!$result) {
$json = array(
'result'=>false,
'message'=>'fail to connect to the server'
);
// covert the response to json format
$response = json_encode($json);
echo $response;
die();
}
$json = array(
'result'=>true,
'message'=>'Success!'
);
$response = json_encode($json);
echo $response;
?>
解决方案
推荐阅读
- python - 列表理解乘以自身,并且不根据条件进行检查
- java - Apache-poi:自动设置合并单元格的大小并使字体加粗
- reflection - 使用反射获取模块的所有 let 绑定
- javascript - 你能给出链接数值并将几个加在一起吗
- javascript - 为什么当我删除搜索字段中的输入过快时结果不会消失?(Javascript)
- python - 如何使用 pandas 水平堆叠基于试验的数据
- python - Pandas - 使用 .apply() 根据条件更新行中的值
- r - R Shiny:出现错误“没有循环中断/下一个,跳转到顶层”
- javascript - 根据文本中的后退箭头符号拆分文本
- javascript - 如何在使用 onFocus 事件打开菜单后取消对按钮的关注