javascript - 用 PHP 和 AJAX 编写代码来记录用户的屏幕尺寸
问题描述
我正在编写一个记录用户屏幕大小的代码,然后将它们重定向到另一个网站,但似乎无法正常工作。我不知道错误在哪里,因为我已经多次修改了语法,一切似乎都很好。这是使用的代码示例:
索引.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<title>My Title</title>
<link rel="shortcut icon" href="./Logo.png"/>
</head>
<body onload="process()">
<script>
var xmlHttp = createXmlHttpRequestObject ();
function createXmlHttpRequestObject () {
var xmlHttp;
// if running Internet Explorer 6 or older
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp)
alert ("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
function process () {
height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
xmlHttp.open("POST", "screenRecorder.php", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send("height=" + height + "&width=" + width);
} else
setTimeout('process()', 1000);
}
function handleRequestStateChange () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
try {
HandleServerResponse();
} catch(e) {
alert("Error reading the response: " + e.toString());
}
}
}
}
function HandleServerResponse () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var response = xmlHttp.responseText;
if (response == 'OK') {
window.location.replace("My URL");
} else {
setTimeout('process()', 1000);
}
}
}
}
</script>
</body>
</html>
和 screenRecorder.php
<?php
class DB {
private static function connect () {
$pdo = new PDO('mysql:host=myhost;dbname=mydbname;charset=utf8', 'myusername', 'mypassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query ($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
$height = $_POST['height'];
$width = $_POST['width'];
if (!empty($height) && !empty($width)) {
DB::query('INSERT INTO screens VALUES(:height, :width)', array(':height'=>$height, ':width'=>$width));
echo 'OK';
} else {
echo 'NO';
}
?>
解决方案
你的 JS 代码永远不会运行。您需要process();
在 JS 代码的末尾添加。
推荐阅读
- node.js - ExcelJS - TypeError:s.createWriteStream 不是函数
- html - 调整网络浏览器大小时,如何防止元素/图像移动?
- linux-containers - 如何遍历容器的pid命名空间?
- javascript - Lodash油门多次点火
- c# - 如何使用winforms从mysql保存加载富文本
- javascript - 如何使用 html 和 css 以及 java 脚本创建多页 pdf 预览?
- unity3d - 如何在 Unity 中创建可在 Web 上玩的在线游戏?
- c++ - 尝试运行 c++ 文件,但它说 launch.json 需要更新其包含路径
- vb.net - 使用 VB.NET 设置壁纸时出现黑屏
- c++ - 使用 glfwGetRequiredInstanceExtensions 指定扩展后,VkWin32SurfaceCreateInfoKHR 不可用