简单的一个js获取php api接口显示公告的html网页案例
代码仅供参考,具体使用的话需要根据业务需求,修改:
1、数据库连接文件及相关信息
2、json数据格式{"text":"公共内容","sotr":"10"}
(sotr单词错误的原因是因为数据库字段别人弄错了,所以我只能这样写哈哈哈)
3、sotr就是用来定义弹窗弹出时间间隔的,简单依赖于本地缓存
4、确保get_announcement.php文件和html代码在同一个域名下,如果路径不一样,则注意修改xhr请求中的路径!
html代码
 <style>
        /* 弹窗背景 */
        .popup-overlay {
            display: none; /* 默认不显示 */
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9999;
        }
        /* 弹窗内容 */
        .popup-content {
            position: fixed;
            top: 35%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            width: 300px;
            text-align: center;
            font-family: Arial, sans-serif;
        }
        .popup-content h2 {
            font-size: 18px;
            margin-top: -10px;
            color: #333;
            text-align: left;
        }
        .popup-content p {
            color: #555;
            margin: 10px 0;
            text-align: left;
        }
        .popup-btn {
            background-color: #007BFF;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        .popup-btn:hover {
            background-color: #0056b3;
        }
    </style>
 <!-- 弹窗结构 -->
<div class="popup-overlay" id="popup-overlay"> <!-- 默认隐藏 -->
    <div class="popup-content">
        <h2>公告</h2>
        <hr>
        <!-- 弹窗内容 -->
        <div id="announcement-content"></div> <!-- 用于显示公告内容 -->
        <button class="popup-btn" id="close-popup-btn">确认</button>
    </div>
</div>
<script>
    // 异步获取公告内容和排序时间
    function fetchAnnouncement() {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'get_announcement.php', true);
        xhr.onload = function() {
            if (this.status === 200) {
                // 处理服务器返回的 JSON 数据
                try {
                    const response = JSON.parse(this.responseText);  // 尝试解析 JSON
                    const text = response.text;  // 公告内容 (可能包含 HTML 标签)
                    const sotr = parseInt(response.sotr, 10);  // sort值字段,转换为整数
                    // 将公告内容(HTML 格式)插入到弹窗中
                    document.getElementById('announcement-content').innerHTML = text;
                    checkAndShowPopup(sotr);  // 使用服务器返回的sotr值作为弹窗间隔时间
                } catch (e) {
                    console.error("获取公告内容JSON解析失败:", e);
                    console.error("获取公告内容返回的数据是:", this.responseText);
                }
            }
        };
        xhr.send();
    }
    // 检查是否需要显示弹窗
    function checkAndShowPopup(popupInterval) {
        //console.log("输出信息,弹窗间隔时间");
        //console.log(popupInterval);
        let lastPopupTime = localStorage.getItem('lastPopupTime');
        const currentTime = Math.floor(Date.now() / 1000); // 当前时间戳(秒)
        // 判断是否需要显示弹窗
        if (!lastPopupTime || currentTime - lastPopupTime >= popupInterval) {
            // 如果是第一次或超过预设的时间间隔,显示弹窗
            document.getElementById('popup-overlay').style.display = 'block';
        }
        // 关闭弹窗的操作
        document.getElementById('close-popup-btn').addEventListener('click', function() {
            document.getElementById('popup-overlay').style.display = 'none';
            // 更新缓存中的上次弹窗时间
            localStorage.setItem('lastPopupTime', currentTime);
        });
    }
    // 页面加载完成后,获取公告内容
    document.addEventListener('DOMContentLoaded', function() {
        fetchAnnouncement(); // 获取公告内容
    });
</script>get_announcement.php
<?php
//获取公共api接口
include('Connections/conn.php'); // 引入数据库连接
// 设置错误报告级别
error_reporting(E_ALL);
ini_set('display_errors', '1');
// 查询数据库获取公告内容和排序字段
$query = "SELECT text, sotr FROM fw_news WHERE id = 35";
$result = mysql_query($query, $conn);
if (!$result) {
    // 如果查询失败,则输出错误信息
    die('Error querying database: ' . mysql_error());
}
$data = mysql_fetch_assoc($result);
if (!$data) {
    // 如果没有获取到数据,则输出错误信息
    die('Error fetching data: ' . mysql_error());
}
// 返回JSON格式的数据
header('Content-Type: application/json');
echo json_encode($data);
mysql_close($conn);
?>