本文将演示如何使用 PHP 从数据库中检索数据,并将其通过 AJAX 请求以 JSON 格式传递给 JavaScript,最终在 HTML 页面上展示。重点解决 JSON 解析错误,并提供清晰的代码示例和步骤说明。
首先,我们需要一个 PHP 函数来从数据库中检索数据,并将其编码为 JSON 格式。以下是一个示例:
关键点:
接下来,我们需要使用 JavaScript 通过 AJAX 请求从 PHP 脚本获取数据,并将其解析为 JavaScript 对象,最后将其展示在 HTML 页面上。
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("
" + name + ": " + user_post + "
"); } }, error: function(xhr, status, error) { console.error("AJAX 请求失败: " + status + " - " + error); console.log(xhr.responseText); // 输出完整的响应内容,方便调试 } }); } $(document).ready(function() { displayPosts(); });
关键点:
HTML 代码部分保持不变,用于展示数据:
Create post:
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.
Like Comment Report通过以上步骤,你应该能够成功地使用 PHP 从数据库中检索数据,并将其通过 AJAX 请求以 JSON 格式传递给 JavaScript,最终在 HTML 页面上展示。 记住,仔细检查错误信息,并使用调试工具来帮助你找到问题所在。