我有一個用 PHP/MySqL、AJAX 和 Jquery 實作的“喜歡”按鈕,每次增加 1 喜歡。一切似乎都很好,并用新值更新了資料庫;但是,從 AJAX 呼叫回傳的回應將回傳我的 .php 檔案中的所有 html,這些 html 位于我的 index.php 中的 post 處理程式之前。除了將處理程式一直移動到頁面頂部之外,有沒有辦法解決這個問題?
代碼如下:
索引.php
<?php
include './includes/header.php';
?>
<?php
include './includes/title_box.php';
?>
<?php
include './includes/categories_box.php';
?>
<?php
include './includes/roadmap_box.php';
?>
<?php
if(isset($_POST['liked'])) {
$postid = $_POST['postid'];
$query = "SELECT * FROM posts WHERE post_id=$postid";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$n = $row['post_upvotes'];
$query = "UPDATE posts SET post_upvotes=$n 1 WHERE post_id=$postid";
mysqli_query($connection, $query);
echo $n 1;
exit();
}
?>
<button class="upvote-button" value=<?php echo $id ?>><?php echo $upvotes ?></button>
腳本.js
$(document).ready(function(){
$(".upvote-button").click(function(){
var postID = $(this).val();
$post = $(this);
$.ajax({
url: './index.php',
type: 'post',
data: {
'liked': 1,
'postid': postID
},
success: function(response){
$post.html(response);
}
});
});
});
控制臺日志(回應)
element.style {
}
user agent stylesheet
body {
display: block;
margin: 8px;
}
?
script.js:14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<title>Product Feedback App</title>
</head>
<body><div class="title-box">
<h1>Frontend Mentor</h1>
<p>Feedback Board</p>
</div><div class="categories-box">
<ul>
<li><a href="index.php">All</a></li>
<li><a href="index.php?category=1">UI</a></li>
<li><a href="index.php?category=3">UX</a></li>
<li><a href="index.php?category=4">Enhancement</a></li>
<li><a href="index.php?category=5">Bug</a></li>
<li><a href="index.php?category=6">Feature</a></li>
</ul>
</div>
<div class="roadmap-box">
<h2>Roadmap</h2>
<a href="./roadmap.php">View Roadmap</a>
<ul>
<li>Planned - 2</li>
<li>In-Progress - 3</li>
<li>Live - 1</li>
</ul>
</div>
134
uj5u.com熱心網友回復:
將您if(isset($_POST['liked']))和所有關聯的代碼移動到一個單獨的檔案中,并在您的 Ajax 查詢 url 中呼叫該檔案。
您可能還需要在新檔案中包含連接到您的資料庫的檔案,但是如果沒有看到包含檔案的內容,就很難給出具體的建議。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/326297.html
