【发布时间】:2021-01-04 11:38:26
【问题描述】:
我正在做一个项目,我想知道在使用 php 或 jQuery 结构之间在具有复杂结构 html 的数据库上插入记录后,哪种是显示数据的最佳方式,为什么?
场景示例:
我正在构建一个帖子和 cmets 系统。当用户编写帖子并发布它时,调用 ajax 触发函数 php 并将信息插入数据库。直到这里一切正常,但是我必须在用户的墙上显示消息插入,那么显示该帖子插入的最佳方式是什么?
有这么多不同的方式,但在速度、安全性和兼容性方面,哪种方式最好?
一些例子,欢迎提出建议:
<script> // default example of call ajax
$.ajax({
type: "POST",
url: 'http://localhost/ajax_ouput_post',
dataType: 'json',
data: { id_user : 1, title : "Hello everyone", content : "Good morning" },
success: function(html) {
// output under php example
},
error: function(){
alert('Error on ajax call');
}
});
</script>
1- 我在 php 中为输出创建模板。
<?php
function ajax_output_post() {
$title = $_POST['title'];
$content = $_POST['content'];
$id_user = $_POST['id_user'];
// all the check for the input
$query = // insert data on mysql @return id_post;
$select_last_post_mysql = // select the last query from the db using id_user and id_post
foreach ($select_last_post_mysql as $post) {
$template = // html structure;
$template .= // continue html structure;
if ($post->photo == 1) {
$template .= // <div>photo user</div>
}
$template .= // ecc...
}
echo json_encode(array('template' => $template));
}
?>
jquery 输出
<script>
$(#wall).append(html.template);
</script>
带有输出 jQuery 模板的 php 第二个示例
<?php
function ajax_output_post() {
$title = $_POST['title'];
$content = $_POST['content'];
$id_user = $_POST['id_user'];
// all the check for the input
$query = // insert data on mysql @return id_post;
$select_last_post_mysql = // select the last query from the db using id_user and id_post
foreach ($select_last_post_mysql as $post) {
$title_json = $post->title;
$content_json = $post->content;
if ($post->photo == 1) {
$photo_user_json = $post->photo_user;
} else {
$photo_user_json = "";
}
$id_post = $post->id_post;
}
echo json_encode(array('title' => $title_json, 'content' => $content_json, 'id_post' => $id_post));
}
?>
jquery
<script>
// in jquery
var Template = {
main_container: "<div class='post_container' data-post='" + html.id_post + "'>",
title: "<div class='title'>" + html.title + "</div>",
content: "<div class='content'>" + html.content + "</div>",
close_main: "</div>",
run: function() {
return Template.main_container + Template.content + Template.close_main;
}
};
$('#wall').append(Template.run());
</script>
【问题讨论】: