蓝极冰焰 2024-05-23 14:33 采纳率: 40.7%
浏览 11
已结题

关于php页面调取、更新数据提交刷新等问题

我有一个页面是j_center.php,包含一个

标签,里面可以加载显示jl.php、fa.php、pf.php等其他文件内容,
在jl.php文件中,通过登录的用户名调取到m_date表中的judge_un字段的对应数据,其中有一个字段是now,用以更新日程状态,
在调取出来的表格中,在now一列,调取初始now状态数据,并且添加下拉菜单:已结束、即将开始、正在进行3个下拉菜单,通过选择的下拉菜单,提交更新到m_date表中,更新now字段数据,并使这些数据更新和显示在jl.php页面中,但不使页面发生跳转,以下是jl.php页面代码和j_center.php页面代码,请各位帮我看看有什么问题,为什么无法提交和更新数据?谢谢
jl.php

<?php 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once './connections/games.php';
session_start();

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true && isset($_SESSION['username'])) {
    $username = $_SESSION['username'];

    $sql = "SELECT username FROM judges WHERE username = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$username]);
    $username_row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($username_row) {
        $username = $username_row['username'];
        // 调取裁判用户名作为索引
    } else {
        echo "没有找到匹配的用户信息。";
    }
} else {
    header("Location: login.php");
    exit;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
    <style>
            table {
            width: 100%; /* 表格宽度为100% */
            border-collapse: collapse; /* 边框合并为一个单一的边框 */
            margin-bottom: 20px; /* 表格底部外边距 */
            background:#777;
            }

            /* 表格头部样式 */
            th {
                background-color: #333; /* 表头背景色 */
                color: #fff; /* 表头文字颜色 */
                padding: 10px; /* 内边距 */
                text-align: center; /* 文字左对齐 */
            }

            /* 表格行样式 */
            tr:nth-child(even) {
                background-color: #555; /* 偶数行背景色 */
            }

            /* 表格数据样式 */
            td {
                padding: 8px; /* 内边距 */
                border: 1px solid #ddd; /* 边框 */
                font-size: 12px; /* 文字尺寸 */
            }

            /* 鼠标悬停样式 */
            tr:hover {
                background-color: #e5e5e5; /* 鼠标悬停时背景色 */
                color: #333;
            }
    </style>
<title></title>
</head>
<body>    
<!--选定之后,显示比赛信息区域 -->
    <p></p>
    <?php
         $sql = "
         SELECT *
         FROM 
             m_date
         WHERE
             judge_un = :judge_un
         ORDER BY
             `order` ASC
     ";
     $stmt = $pdo->prepare($sql);
     $stmt->bindParam(':judge_un', $username); // 使用绑定参数来避免SQL注入
     $stmt->execute();
     $order = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ?>

<!--选定之后,显示比赛信息区域 -->
<p></p>
<h3>竞赛日程 | Date Of Date</h3>
<a>共有项比赛,已完成项,还有项待完成</a>
<main id="content">
        <!-- 这里将通过AJAX加载j_center.php的内容 -->
    </main>
<div style="border-radius: 20px; background-color:#F8F8F8;">
    <form id="updateForm">
    <table style="font-family: inherit;color:#FFF">
        <tr align="center" style="font-weight:bold;font-size:12px;">
         <th>顺序<br>Order</th>
         <th>状态<br>State</th>
         <th>计划时间<br>Time</th>
         <th>组别<br>Group</th>
         <th>项目<br>Event</th>
         <th>赛程<br>Schedule</th>
         <th>人数<br>Count</th>
         <th>备注<br>Remark</th>
         </tr>
         <?php
        foreach ($order as $row):
        ?>
         <tr align="center" style="font-weight:bold;font-size:10px;">
         <td><?php echo htmlspecialchars($row['id']);?></td>
         <td>
             <select id="now_<?php echo $row['id']; ?>" name="now_<?php echo $row['id']; ?>">
                <option value="已完成" <?php echo ($row['now'] == '已完成') ? 'selected' : ''; ?>>已完赛</option>
                <option value="进行中" <?php echo ($row['now'] == '进行中') ? 'selected' : ''; ?>>正在进行</option>
                <option value="即将开始" <?php echo ($row['now'] == '即将开始') ? 'selected' : ''; ?>>即将开始</option>
            </select>
            <button type="button" class="updateButton" data-id="<?php echo $row['id']; ?>">更新赛程</button>
        </td>
         <td><?php echo htmlspecialchars($row['time']); ?></td>
         <td><?php echo htmlspecialchars($row['group']); ?></td>
         <td><?php echo htmlspecialchars($row['event']); ?></td>
         <td><?php echo htmlspecialchars($row['schedule']); ?></td>
         <td><?php echo htmlspecialchars($row['athletes']); ?></td>
         <td><?php echo htmlspecialchars($row['remark']); ?></td>
         </tr>
         <?php
        endforeach;
        ?>
    </table>
    </form>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            // 绑定点击事件到所有的更新按钮
            $('.updateButton').on('click', function() {
                var button = $(this);
                var id = button.data('id');
                var newValue = $('#now_' + id).val(); // 获取对应select的值
                
                if (!id || !newValue) {
                    alert('缺少必要的参数,请检查您的HTML结构。');
                    return;
                }

                $.ajax({
                    url: 'update_status.php',
                    type: 'POST',
                    data: { id: id, now: newValue },
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            // 更新成功后加载新的<main>内容
                            loadMainContent();
                        } else {
                            alert('更新失败:' + response.message);
                        }
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        alert('更新时发生错误:' + textStatus);
                    }
                });
            });
            
            // 定义一个函数来加载<main>标签的内容
            function loadMainContent() {
                $.ajax({
                    url: 'j_center.php', // 假设j_center.php返回完整的页面内容或仅<main>标签的内容
                    type: 'GET', // 或者POST,取决于您的后端处理逻辑
                    success: function(data) {
                        // 如果j_center.php返回的是整个页面的内容,您可能需要使用某种方式来提取<main>标签的内容
                        // 例如,使用jQuery选择器来选择<main>标签的内容:$(data).find('main').html()
                        // 假设j_center.php只返回<main>标签的内容,则直接更新<main>标签
                        $('main-content').html(data);
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        alert('加载内容时发生错误:' + textStatus);
                    }
                });
            }
            
            // 页面加载完成后立即加载<main>标签的内容(可选)
            loadMainContent();
        });                     
    </script>

</body>
</html>


j_center.php

<?php
// 启用错误报告
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once './connections/games.php';

// 启动会话
session_start();

// 检查用户是否已登录
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true && isset($_SESSION['username'])) {
    $username = $_SESSION['username'];

    // 准备SQL查询语句
    $sql = "SELECT * FROM judges WHERE username = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    // 检查是否获取到用户信息
    if ($user) {

    } else {
        // 没有找到匹配的用户信息
        echo "没有找到匹配的用户信息。";
    }
} else {
    // 用户未登录,重定向到登录页面
    header("Location: login.php");
    exit;
}

// 检查会话中是否有选中的数据
if (isset($_SESSION['selected_data']) && is_array($_SESSION['selected_data'])) {
    // 获取选中的数据
    $selectedData = $_SESSION['selected_data'];

    // 清除会话中的数据(可选,如果你不想在后续请求中重复使用这些数据)
    unset($_SESSION['selected_data']);
} else {
    // 如果没有选中的数据,设置一个空数组或进行其他处理
    $selectedData = array();
}
// 显示页面内容
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>裁判管理中心 | For Judges</title>
    <link rel="icon" href="image/logof.png" type="image/png">
    <link href="../css/judges.css" rel="stylesheet" type="text/css">
    <style>
                /* 使用 flex 布局让图片和文字在同一行 */
        .link-logo {
            display: flex;
            align-items: center; /* 垂直居中 */
        }

        .span-width {
            display: inline-block; /* 或者使用 'block' */
            width: 100px; /* 设置你想要的宽度 */
            height: 20px;
            background-color: #0099cc; /* 可选的背景色,用于可视化span的宽度 */
            color:#FFF;
            font-weight:bold;
            border-radius: 10px;
            text-align: center; /* 可选的文本居中 */
        }
        .span-xg {
            display: inline-block; /* 或者使用 'block' */
            width: 80px; /* 设置你想要的宽度 */
            height: 16px;
            background-color: #b0b0b0; /* 可选的背景色,用于可视化span的宽度 */
            color:#FFF;
            font-size:8px;
            border-radius: 10px;
            text-align: center; /* 可选的文本居中 */
        }
                    /* 鼠标悬停样式 */
        span:hover {
                background-color: #0099cc; /* 鼠标悬停时背景色 */
            }
        .logo {
            width: 150px; /* 设置LOGO的宽度 */
            height: 150px; /* 设置LOGO的高度 */
            transition: all 0.3s ease; /* 添加过渡效果,使变化更平滑 */
        }
        .logo:hover {
            transform: scale(1.1); /* 鼠标悬停时放大1.1倍 */
        }
        table {
                width: 100%; /* 表格宽度为100% */
                border-collapse: collapse; /* 边框合并为一个单一的边框 */
                margin-bottom: 20px; /* 表格底部外边距 */
            }

            /* 表格头部样式 */
            th {
                background-color: #2b7acd; /* 表头背景色 */
                color: #fff; /* 表头文字颜色 */
                padding: 10px; /* 内边距 */
                text-align: center; /* 文字左对齐 */
            }

            /* 表格行样式 */
            tr:nth-child(even) {
                background-color: #f2f2f2; /* 偶数行背景色 */
            }

            /* 表格数据样式 */
            td {
                padding: 8px; /* 内边距 */
                text-align: center; 
                border: 1px solid #ddd; /* 边框 */
            }

            /* 鼠标悬停样式 */
            tr:hover {
                background-color: #e5e5e5; /* 鼠标悬停时背景色 */
            }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            // 加载 grxx.php 到 <main> 标签
            $('#load_grxx').click(function(e) {
                e.preventDefault();
                $('#main-content').load('grxx.php', function() {
                    // grxx.php 内容加载完成后的回调函数
                });
            });

            // 加载 zcjl.php 到 <main> 标签
            $('#load_zcjl').click(function(e) {
                e.preventDefault();
                $('#main-content').load('zcjl.php', function() {
                    // zcjl.php 内容加载完成后的回调函数
                });
            });
            
        });
    </script>
</head>
<body>
    <div class="app">
    <header class="header">
        <span><h1>中心</h1></span>
    </header>
    <div class="container">
        <aside class="left">
            <div role="group" aria-label="Button group with nested dropdown">
                <button class="button" type="button" id="load_grxx">个人信息<br>Personal</button>
                <div class="dropdown">
                    <button class="dropdown-button button" type="button" id="load_zczx">zczx<br>Referee position</button>
                    <ul class="dropdown-content">
                        <li><a href="#" onclick="loadContent('jl.php')">● jl</a></li>
                        <li><a href="#" onclick="loadContent('pf.php')">● pf</a></li>
                        <li><a href="#" onclick="loadContent('ff.php')">● ff</a></li>

                    </ul>
                </div>
                <button class="button" type="button" id="load_zcjl">zcjl<br>curriculum vitae</button>
                <button class="button" type="button" onclick="window.location.href='index.php';">退出登录<br>Login Out</button>
            </div>
        </aside>
        <div class="main">
            <div style="background:#ededed">欢迎登录!<b><?php echo htmlentities($user['realname']) ; ?></b>
            <?php
            if ($user) {
                $beginDate = $user['reg_time'];
                $startDate = new DateTime($beginDate);
                $currentDate = new DateTime();
                $interval = $startDate->diff($currentDate);
                $years = $interval->y;
                $days = $interval->days;
                if ($days >= 365) {
                    $extraYears = floor($days / 365);
                    $days %= 365; 
                }
                echo $years . "年" . ($days > 0 ? $days . "天;" : "");
            } else {
                echo "No begin_date found for user ID $userId";
            }
            ?>,来自<?php echo htmlentities($user['area']); ?>-<?php echo htmlentities($user['city']); ?>
    </div>
    <main id="main-content">
    </main>
    </div>
    </div>
    </div>
    <script>
    function loadContent(page) {
        // 获取<main>标签
        var content = document.getElementById('main-content');
        
        // 创建XMLHttpRequest对象
        var xhr = new XMLHttpRequest();
        
        // 设置请求完成时的回调函数
        xhr.onload = function() {
            if (xhr.status === 200) {
                // 请求成功,将返回的内容加载到<main>标签中
                content.innerHTML = xhr.responseText;
            } else {
                // 请求失败,显示错误信息
                content.innerHTML = 'Error loading the page.';
            }
        };
        
        // 发起GET请求到指定页面
        xhr.open('GET', page, true);
        xhr.send();
        
        // 阻止默认的链接跳转行为
        return false;
    }

</script>
</body>
</html>


update_status.php:


<?php
// update_status.php
// 引入数据库连接文件
require_once './connections/games.php';
// 开启错误报告
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
 
// 检查请求方法是否为POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 假设你已经进行了用户认证和权限检查

    // 获取POST数据
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $now = isset($_POST['now']) ? $_POST['now'] : '';

    // 准备SQL语句
    $stmt = $pdo->prepare("UPDATE m_date SET now = :now WHERE id = :id");

    // 绑定参数并执行
    $stmt->bindParam(':now', $now);
    $stmt->bindParam(':id', $id);
    $result = $stmt->execute();

    // 检查更新是否成功
    if ($result) {
        echo '状态更新成功';
    } else {
        echo '状态更新失败';
    }
} else {
    echo '无效的请求方法';
}
?>

  • 写回答

17条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-05-23 14:38
    关注

    引自免费微信小程序:皆我百晓生

    要解决你在PHP页面调取数据、更新数据提交刷新过程中遇到的问题,我们首先确保所有相关脚本(j_center.php, update_status.php, 和前端的JavaScript部分)协同工作无误。下面我会逐一分析并提供解决方案。

    j_center.php 的优化与问题解决

    1. 动态加载内容:你的页面中通过AJAX加载j_center.php的部分内容,但实际代码中并未直接体现此功能。确保loadMainContent函数正确地从服务器获取数据并更新至<main>标签内。这可以通过将j_center.php中展示数据的部分独立出来,或者确保当调用loadMainContent时,服务端返回的正是所需的数据片段。

    2. 表单元素ID与更新逻辑:你为每个赛程的状态更新准备了按钮和对应的select标签,确保它们能正确地与JavaScript的点击事件处理函数关联,并且通过AJAX向update_status.php发送更新请求。

    update_status.php 的确认

    1. 安全性验证:虽然代码中已使用预处理语句来防止SQL注入,但确保在实际部署前,用户权限和会话验证也得到妥善处理,以防非法访问直接通过URL调用此脚本。

    2. 响应格式:在成功或失败的情况下,脚本返回的是简单的字符串消息。为了更好的前后端交互,可以考虑返回JSON格式,例如:{"status": "success", "message": "状态更新成功"}。这样前端能更方便地根据status字段判断操作结果。

    前端JavaScript逻辑完善

    1. 加载内容的回调处理:在loadMainContent函数中,成功获取数据后,确保使用.html(data)正确更新DOM元素,注意这里的元素选择器应当与你的HTML结构相匹配,若<main>标签的ID为main-content,则保持不变。

    2. 错误处理增强:在AJAX请求中,除了处理success回调,也应当完善error回调的逻辑,以便于调试和用户体验,比如提供更具体的错误信息提示。

    综合示例代码调整

    j_center.php 中的<main>加载逻辑示例

    <main id="content">
        <!-- 这里原本应由AJAX动态填充内容 -->
    </main>
    <script>
        function loadMainContent() {
            $.ajax({
                url: 'j_center.php', // 确保这里返回你需要加载的那部分内容
                type: 'GET',
                success: function(data) {
                    $('#content').html(data); // 正确更新内容区域
                },
                error: function(xhr, status, error) {
                    console.error('加载内容时出错:', status, error);
                }
            });
        }
        loadMainContent(); // 页面加载时初始化加载
    </script>
    

    update_status.php 返回JSON示例

    // 成功更新后
    echo json_encode(['status' => 'success', 'message' => '状态更新成功']);
    exit;
    
    // 失败时
    echo json_encode(['status' => 'error', 'message' => '状态更新失败']);
    exit;
    

    前端AJAX错误处理增强

    $.ajax({
        // ... 其他配置
        error: function(jqXHR, textStatus, errorThrown) {
            alert('更新时发生错误: ' + textStatus + ' - ' + errorThrown);
        }
    });
    

    通过以上调整,你的页面应该能够实现数据的动态加载、状态更新,并在每次更新后刷新相关内容区域,同时提供了更健壮的错误处理机制。记得测试每个环节确保逻辑连贯,无遗漏。

    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 5月25日
  • 创建了问题 5月23日