
本文将演示如何使用 PHP 从数据库中检索数据,并将其通过 AJAX 请求以 JSON 格式传递给 JavaScript,最终在 HTML 页面上展示。重点解决 JSON 解析错误,并提供清晰的代码示例和步骤说明。
首先,我们需要一个 PHP 函数来从数据库中检索数据,并将其编码为 JSON 格式。以下是一个示例:
<?php
function retrieve_post($connection) {
$sql = "SELECT * FROM tbl_user_posts";
$result = mysqli_query($connection, $sql);
// 确保查询成功执行
if (!$result) {
die("查询失败: " . mysqli_error($connection));
}
// 将结果集转换为关联数组
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
// 将数据编码为 JSON 格式
header('Content-Type: application/json'); // 设置响应头,告诉浏览器返回的是 JSON 数据
echo json_encode($data);
}
// 示例用法(假设你已经建立了数据库连接 $connection)
// retrieve_post($connection);
?>关键点:
接下来,我们需要使用 JavaScript 通过 AJAX 请求从 PHP 脚本获取数据,并将其解析为 JavaScript 对象,最后将其展示在 HTML 页面上。
立即学习“PHP免费学习笔记(深入)”;
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
function displayPosts(){
$.ajax({
type: "POST",
url: "main_page.php", // 确保 URL 正确
dataType: "json", // 显式指定返回的数据类型为 JSON
success: function(response) {
// response 已经是 JavaScript 对象,无需再次解析
console.log(response);
// 遍历数据并展示
for (var i = 0; i < response.length; i++) {
var row = response[i];
var name = row.name;
var user_post = row.user_post;
console.log(name, user_post);
// 在 HTML 中展示数据 (示例)
$("#posted").append("<p>" + name + ": " + user_post + "</p>");
}
},
error: function(xhr, status, error) {
console.error("AJAX 请求失败: " + status + " - " + error);
console.log(xhr.responseText); // 输出完整的响应内容,方便调试
}
});
}
$(document).ready(function() {
displayPosts();
});关键点:
HTML 代码部分保持不变,用于展示数据:
<div class="user-post">
Create post:<br>
<form id="form" method="POST">
<textarea id = "create_post" name="create_post" rows="10" cols = "50"></textarea>
<input type="submit" class="post-button" value="PostButton" onclick = submit_post()>
</form>
</div>
<div class="posts" id="posted">
<div class="post">
<h3 id="existing_posts"><img src="default-pic.png" class="profile-pic" alt="Default Picture" width="50" height="50">Posts</h3>
<p>This is an example of a post. It will need to be boxed and made so that the name of the user goes above
the name of the likes and dislikes of the posts are to the left of the post and that the reply and report
functionalities are at the bottom right of the posts. It will also need a box around it to show where the post starts and ends.</p>
<div class="options">
<a href="">Like</a>
<a href="">Comment</a>
<a href="" class="report">Report</a>
</div>
</div>
</div>通过以上步骤,你应该能够成功地使用 PHP 从数据库中检索数据,并将其通过 AJAX 请求以 JSON 格式传递给 JavaScript,最终在 HTML 页面上展示。 记住,仔细检查错误信息,并使用调试工具来帮助你找到问题所在。
以上就是使用 PHP 和 AJAX/JSON 将数据传递给 JavaScript的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号