以下是一个简化的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可以写入文件。此代码不包括错误处理,应该在实际应用中添加错误处理逻辑。