You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP将MySQL数据转为JSON并在HTML页面使用(WordPress场景)

WordPress中PHP查询MySQL并返回JSON在HTML展示的解决方案

一、PHP代码修正

原代码存在查询方法错误、结果处理不当等问题,以下是修正后的代码:

if (isset($_POST['notes_section'])) {
    $notesSection = $_POST['notes_section'];

    // 准备SQL查询语句,仅传递占位符对应参数
    $sql = $wpdb->prepare(
        "SELECT * FROM wp_activity_notes WHERE userId = %d AND postId = %d AND siteId = %d ORDER BY id DESC",
        $user_id, 
        $notesSection, 
        $site_id
    );
    
    // 使用get_results获取多条记录,OBJECT指定返回对象格式的数组
    $notesList = $wpdb->get_results($sql, OBJECT);
    
    // 整理前端需要的字段到数组
    $jsonArray = [];
    foreach ($notesList as $note) {
        $jsonArray[] = [
            'timestamp' => $note->timestamp, // 需确保表中存在该字段,字段名不符则修改
            'user_note' => $note->notes
        ];
    }

    // wp_send_json_success自动完成JSON编码并返回响应
    wp_send_json_success($jsonArray);
}

修改说明

  • 替换$wpdb->get_var为$wpdb->get_results:前者仅返回单个值,后者用于获取多条查询结果
  • 调整OBJECT参数位置:该参数是get_results的格式指定项,不应传入prepare中
  • 正确收集结果:初始化空数组后,通过循环追加每条记录的指定字段,避免覆盖数据
  • 移除冗余的json_encode:wp_send_json_success会自动完成JSON编码并设置响应头

二、AJAX代码修正

原代码无法处理多条记录,且存在语法错误,以下是修正后的代码:

$(document).on("click", ".get_notes", function(e){
    e.preventDefault();
    const notesSection = $(this).data("notes-section");
    
    $.ajax({
        url: WP.ajax_url,
        type: 'POST',
        dataType: 'json',
        data: {
            'action': 'notes',
            'notes_section' : notesSection
        },

        success: function(response) {
            if (response.success === true) {
                const notes = response.data;
                // 清空笔记容器,需确保HTML中存在该容器
                const notesContainer = $(".notes-container");
                notesContainer.empty();
                
                // 循环渲染每条笔记到页面
                notes.forEach(note => {
                    const noteHtml = `
                        <div class="note-item">
                            <div class="notes-timestamp">${note.timestamp}</div>
                            <div class="notes-user-note">${note.user_note}</div>
                        </div>
                    `;
                    notesContainer.append(noteHtml);
                });
            }
        },
        error: function(xhr, status, error) {
            console.error("获取笔记失败:", error);
        }
    });
});

修改说明

  • 修复选择器引号闭合错误:原代码中$(".notes-timestamp)缺少闭合引号
  • 新增笔记容器:通过.notes-container批量渲染多条记录,避免覆盖原有内容
  • 动态生成HTML:循环遍历返回的数组,生成每条笔记的DOM结构并追加到容器中
  • 添加错误回调:便于调试请求失败的情况

补充说明

  • 确保HTML中存在.notes-container元素,作为笔记的承载容器
  • 确认MySQL表wp_activity_notes中的字段名与代码中一致,若timestamp字段名不同需对应修改
  • 确保PHP代码中$user_id和$site_id已正确获取当前用户及站点ID

内容的提问来源于stack exchange,提问作者Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 08:45:25