javascript 记录鼠标移动并将数据存储在数据库中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25260681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Record mouse movements and store data on database
提问by Ellie
Im kind of new to javascript and database manipulation.
我对 javascript 和数据库操作有点陌生。
Is there a way that every time the users enter the page the mouse movements start to get recorded and once the user leaves the page all the data (Coords x and y, and time) are stored on the database for later analysis?
有没有办法每次用户进入页面时,鼠标移动开始被记录下来,一旦用户离开页面,所有数据(坐标 x 和 y 以及时间)都存储在数据库中以供以后分析?
I know many sites do it so there has to be an easy way to do it.
我知道很多网站都这样做,所以必须有一种简单的方法来做到这一点。
An example would be nice, my database is MySql, my site in wordpress.
一个例子会很好,我的数据库是 MySql,我在 wordpress 中的站点。
回答by Manwal
Javascript:
Javascript:
document.onmousemove = function(e){
var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
console.log(pageCoords);
};
Unload javascript:
卸载javascript:
window.onunload=function(){
//SomeJavaScriptCode
};
jQuery:
jQuery:
var pageCoords = []; //array for storing coordinates
$(document).onmousemove = function(e){
pageCoords.push("( " + e.pageX + ", " + e.pageY + " )");//get page coordinates and storing in array
}
$( window ).unload(function() {
//make ajax call to save coordinates array to database
});
UPDATED DEMO
更新的演示
回答by Bradly Spicer
One but very bad way is tracking the location of the mouse and constantly placing the position into the mysql db
一种但非常糟糕的方法是跟踪鼠标的位置并不断将位置放入mysql db
(function() {
window.onmousemove = handleMouseMove;
function handleMouseMove(event) {
event = event || window.event; // IE-ism
// event.clientX and event.clientY contain the mouse position
}
})();
Have a read of this:
请阅读以下内容:
Determine mouse position outside of events (using jQuery)?
and this:
还有这个:
Javascript - Track mouse position
Once you have read them, you'l be able to see that data is being shown in your console. Now we need to send it from the console to PHP and then into mysql.
阅读它们后,您将能够看到数据显示在您的控制台中。现在我们需要将它从控制台发送到 PHP,然后发送到 mysql。
The following explains how: http://www.coderslexicon.com/the-basics-of-passing-values-from-javascript-to-php-and-back/
以下解释了如何:http: //www.coderslexicon.com/the-basics-of-passing-values-from-javascript-to-php-and-back/
Lastly, I suggest reading up on:
最后,我建议阅读:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.query.php
Don't use MySQL queries. Use MySQLi as MySQL is deprecated.
不要使用 MySQL 查询。使用 MySQLi,因为 MySQL 已被弃用。