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

如何将JavaScript变量值传递给PHP变量?无刷新获取客户端屏幕参数

没问题!我来给你捋清楚怎么搞定这个需求——毕竟PHP是跑在服务器上的,根本没法直接拿到用户浏览器的屏幕信息,必须靠前端JavaScript先把这些数据捞出来,再悄悄传给PHP(全程不刷新页面,也不用cookie、session或者GET参数)。我把代码写得超直白,你哪怕不懂AJAX也能直接用,不用纠结细节~

完整实现代码(直接复制就能用)

把下面的代码保存成try.php,直接访问localhost/try.php就能看到效果:

<?php
// 处理前端传来的POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 接收并转成整数(简单过滤,避免非法数据)
    $screenWidth = isset($_POST['width']) ? (int)$_POST['width'] : 0;
    $screenHeight = isset($_POST['height']) ? (int)$_POST['height'] : 0;
    $colorDepth = isset($_POST['colorDepth']) ? (int)$_POST['colorDepth'] : 0;
    $pixelDepth = isset($_POST['pixelDepth']) ? (int)$_POST['pixelDepth'] : 0;

    // 这里可以加你需要的逻辑:比如存数据库、计算比例等等
    $response = [
        'status' => 'success',
        'data' => [
            'screen_width' => $screenWidth,
            'screen_height' => $screenHeight,
            'color_depth' => $colorDepth,
            'pixel_depth' => $pixelDepth
        ]
    ];

    // 返回JSON格式的结果给前端
    header('Content-Type: application/json');
    echo json_encode($response);
    exit; // 处理完POST请求就停止,不要输出后面的HTML
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>获取屏幕信息</title>
    <script>
        // 页面加载完成后自动执行
        window.onload = function() {
            // 1. 用JS获取屏幕的四个关键信息
            const screenData = {
                width: screen.width,
                height: screen.height,
                colorDepth: screen.colorDepth,
                pixelDepth: screen.pixelDepth
            };

            // 2. 悄悄把数据传给PHP(无刷新,用fetch这个简单的AJAX工具)
            fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(screenData)
            })
            .then(res => res.json())
            .then(result => {
                // 把结果显示在页面上,你也可以改成自己需要的逻辑
                document.getElementById('screen-info').innerHTML = `
                    <h3>你的屏幕信息:</h3>
                    <ul>
                        <li>屏幕宽度:${result.data.screen_width}px</li>
                        <li>屏幕高度:${result.data.screen_height}px</li>
                        <li>颜色深度:${result.data.color_depth}位</li>
                        <li>像素深度:${result.data.pixel_depth}位</li>
                    </ul>
                `;
                // 也可以在控制台看结果,方便调试
                console.log('PHP返回的屏幕数据:', result);
            })
            .catch(err => {
                console.error('传输数据出错啦:', err);
            });
        };
    </script>
</head>
<body>
    <div id="screen-info"></div>
</body>
</html>
关键部分说明(怕你需要改逻辑)
  • 前端JS部分:screen.width这些都是浏览器原生提供的属性,直接拿就行;fetch是现在主流的无刷新数据传输方式,我已经把参数配置好了,你不用改就能用。
  • PHP部分:通过$_POST接收数据,POST请求不会把数据暴露在URL里,完全符合你“不用GET参数”的要求;如果需要把数据存数据库或做其他处理,直接在注释标注的位置加代码就行。
  • 为什么不用cookie/session?:这个方案里数据是实时通过POST请求传给PHP的,不需要存在客户端,完全满足你的要求。

内容的提问来源于stack exchange,提问作者Coding with Creativini

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:17:48