AJAX响应包含来自页面的html而不是单个值



我有一个'喜欢'按钮,我已经实现了PHP/MySqL, AJAX和Jquery,每次增量喜欢+1。这一切似乎工作得很好,并更新数据库与新的值;但是,从AJAX调用返回的响应返回的是.php文件中位于index.php中的post处理程序之前的所有html。除了将处理程序一直移动到页面顶部之外,还有什么方法可以解决这个问题吗?

下面的代码:

index . 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> 

script.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);
}
});
});
});

console.log(响应)

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

if(isset($_POST['liked']))和所有相关代码移动到一个单独的文件中,并在Ajax查询url中调用该文件。

您可能还需要在新文件中包含连接到数据库的文件,但是如果没有看到所包含文件的内容,则很难给出具体的建议。

最新更新