如何将从WordPress wp_posts表获取的JSON数据展示为HTML表格
第一步:修复服务端process.php代码
你当前的process.php使用print_r输出调试内容,不符合AJAX接收JSON格式数据的要求,修改后代码如下:
<?php // 先设置JSON响应头,避免前端解析异常 header('Content-Type: application/json'); $query="SELECT * FROM `wp_posts` where ID=30"; $arr_result = []; try { $stmt = $pdo->prepare($query); $stmt->execute(); $row = $stmt->fetch(); $arr_result= array( "id" =>$row['ID'], // 可选优化:提前在PHP把JSON转成数组,前端就不需要再转 // "postcontent" => json_decode($row['post_content'], true) "postcontent" => $row['post_content'] ); } catch(PDOException $e) { $arr_result['error'] = $e->getMessage(); } // 注释调试用的print_r,放开json_encode输出 // print_r($arr_result); echo json_encode($arr_result); ?>
第二步:修改前端JS代码,渲染为HTML表格
你当前的JS没有把postcontent的JSON字符串转成数组,也没有拼接表格结构,修改后代码如下:
$(document).ready(function(){ $.ajax({ url: 'process.php', method:'post', dataType: "json", data:{action:"emplist"}, success: function(data){ // 如果已经在PHP端转好了数组,可删除下面这行JSON.parse代码 const tableData = JSON.parse(data.postcontent); let htmlText = '<table border="1" cellpadding="8" cellspacing="0">'; // 取第一组数据作为表头 const headers = tableData[0]; htmlText += '<thead><tr>'; headers.forEach(header => { htmlText += `<th>${header}</th>`; }); htmlText += '</tr></thead><tbody>'; // 从第二组数据开始循环生成表体内容 for(let i = 1; i < tableData.length; i++) { const row = tableData[i]; htmlText += '<tr>'; row.forEach(cell => { htmlText += `<td>${cell}</td>`; }); htmlText += '</tr>'; } htmlText += '</tbody></table>'; $('body').append(htmlText); }, error: function(xhr, err) { console.error('请求出错:', err); } }); });
注意事项
- 上述代码里的表格边框、内边距等样式仅为基础展示用,你可以自行编写CSS调整表格样式
- 要保证数据库
post_content字段里存储的是合法JSON格式,不要有多余的尾逗号,否则会导致JSON.parse解析失败
内容的提问来源于stack exchange,提问作者user9437856
相关产品推荐
相关产品推荐

