我有一个页面,该页面应将JS AJAX中的数据推入数据库,但是当我使用时
include("../bootstrap.php");
没有任何效果。如果我不考虑它,那么JS可以工作,但是没有任何东西被推送到数据库中。
索引中的JS + AJAX(可以正常工作)
$(document).ready(function(){
$("#submit").on("click", function(e){
var text = $("#NewComment").val();
$.ajax({
method: "POST",
url: "ajax/postcomment.php",
data: {text: text, postId: "<?php echo $postId ?>"},
dataType: "json"
})
.done(function( res ) {
if(res.status == "success") {
<?php foreach($post->getUsername() as $u): ?>
var p =
"<p><span class=\"yellow\"><?php echo $u['firstname'] . ' ' . $u['lastname']; ?></span>: " + text + "</p>";
<?php endforeach; ?>
$("#commentList").append(p);
$("#NewComment").val("").focus();
}
});
e.preventDefault();
});
});
ajax / postcomment.php
<?php
if(!empty($_POST)){
$text = $_POST['text'];
$postId = $_POST['postId'];
include("../bootstrap.php"); //WEIRD ACTING INCLUDE/REQUIRE, PATH IS CORRECT
try{
$comment = new Comment();
$comment->setText($text);
$comment->setPostId($postId);
$comment->save();
$result = [
"status" => "success",
"message" => "Comment Saved"
];
}catch(Throwable $t){
$result = [
"status" => "error",
"message" => "Plz try again"
];
}
$result = [
"status" => "success",
"message" => ">Comment has been saved"
];
echo json_encode($result);
};
带有Comment类的post.php(也可以单独使用)
<?php
class Comment{
private $postId;
private $text;
// POST ID
public function getPostId(){
return $this->postId;
}
public function setPostId($postId){
$this->postId = $postId;
return $this;
}
// COMMENT
public function getText(){
return $this->text;
}
public function setText($text){
$this->text = $text;
return $this;
}
// ADD COMMENT TO DB
public function save(){
$conn = Db::getInstance();
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$statement = $conn->prepare("
INSERT INTO comments (comment_user_id, comment_text, comment_post_id, comment_date)
VALUES (:user_id, :text, :post_id, :date)
");
$statement->bindValue(":post_id", $this->getPostId());
$statement->bindValue(":user_id", $_SESSION['user']);
$statement->bindValue(":text", $this->getText());
$statement->bindValue(":date", strftime("%Y-%m-%d %H:%M:%S"));
return $statement->execute();
}
}
?>
我没有收到任何错误消息,它对include()没有任何作用。仅执行JS,不执行JS / p