使用JavaScript收集和发送用户设备信息,后端使用php将数据保存在本地json,便于后期分析数据
    		       		warning:
    		            这篇文章距离上次修改已过442天,其中的内容可能已经有所变动。
    		        
        		                
                以下是一个简化的JavaScript代码示例,用于收集用户的设备信息并通过AJAX将其发送到一个PHP脚本,该脚本将数据保存到本地的JSON文件中。
JavaScript (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Device Information Collector</title>
</head>
<body>
    <button id="submit">Submit Device Information</button>
 
    <script>
        document.getElementById('submit').addEventListener('click', function() {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'save_device.php', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log(xhr.responseText);
                }
            };
 
            var deviceInfo = {
                userAgent: navigator.userAgent,
                screenResolution: window.screen.width + 'x' + window.screen.height,
                language: navigator.language
            };
 
            xhr.send(JSON.stringify(deviceInfo));
        });
    </script>
</body>
</html>PHP (save\_device.php):
<?php
$data = json_decode(file_get_contents('php://input'), true);
file_put_contents('devices.json', json_encode($data), FILE_APPEND);
echo "Device information saved.";
?>确保save_device.php文件有适当的权限,以便PHP可以写入文件。此代码不包括错误处理,应该在实际应用中添加错误处理逻辑。
评论已关闭