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

如何将WordPress站点JSON API返回的true/false转为在线/离线显示

WordPress中JSON API状态值转换显示方案

你可以通过前端JavaScript或WordPress后端PHP两种方式实现状态值的转换显示,以下是具体实现方法:

一、前端JavaScript实现(动态加载,无需刷新页面)

方法1:原生Fetch API

// 替换为你的API接口地址
fetch('https://your-site.com/api/online-status')
  .then(response => response.json())
  .then(data => {
    // 替换为页面中用于显示状态的元素ID
    const statusElement = document.getElementById('status-display');
    // 根据API返回的online值切换显示文本
    statusElement.textContent = data.online ? '在线' : '离线';
  })
  .catch(error => console.error('获取状态失败:', error));

方法2:jQuery(WordPress默认集成)

// 替换为你的API接口地址
jQuery.ajax({
  url: 'https://your-site.com/api/online-status',
  dataType: 'json',
  success: function(data) {
    const statusText = data.online ? '在线' : '离线';
    // 替换为页面中用于显示状态的元素选择器
    jQuery('#status-display').text(statusText);
  },
  error: function(xhr, status, error) {
    console.log('请求出错:', error);
  }
});

使用时,只需在页面中添加一个用于显示状态的元素:

<div id="status-display"></div>

二、WordPress后端PHP实现(页面渲染时直接生成内容)

在你的WordPress模板文件(如page.php、single.php或自定义模板)中添加以下代码:

// 替换为你的API接口地址
$api_url = 'https://your-site.com/api/online-status';
$api_response = wp_remote_get($api_url);

if (!is_wp_error($api_response)) {
  $response_body = wp_remote_retrieve_body($api_response);
  $status_data = json_decode($response_body, true);
  
  if (isset($status_data['online'])) {
    $display_text = $status_data['online'] ? '在线' : '离线';
    echo '<span class="status-indicator">' . esc_html($display_text) . '</span>';
  } else {
    echo '<span class="status-indicator">状态未知</span>';
  }
} else {
  echo '<span class="status-indicator">获取状态失败</span>';
}

这种方式会在页面加载时直接渲染出状态文本,无需前端额外请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:54:09