网站的 Javascript 命中计数器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11657492/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:55:29  来源:igfitidea点击:

Javascript hit counter for a website

javascript

提问by Luke John Southard

I'm trying to code a hit counter for a website. As a preference, not required, I'm trying to use Javascript to do this. On the website's html file, I'm reading a number from a javascript file and outputting that. How can I make it "count" every time a hit occurs?

我正在尝试为网站编写点击计数器。作为一种偏好,不是必需的,我正在尝试使用 Javascript 来做到这一点。在网站的 html 文件中,我正在从 javascript 文件中读取一个数字并输出该数字。每次发生命中时如何让它“计数”?

Sorry for such a vague question. Am I on the right track going about this? Any tips, code, or references will be much appreciated.

抱歉问了这么模糊的问题。我在正确的轨道上吗?任何提示、代码或参考将不胜感激。

Thanks!

谢谢!

采纳答案by Ibu

Using Javascript you can only count the hits from the current user, because you have to save the count in a cookie or a client side technology.

使用 Javascript,您只能计算当前用户的点击次数,因为您必须将计数保存在 cookie 或客户端技术中。

For a more accurate way you have to use a server-side language and maybe add a storage engine like a database to make it work.

要获得更准确的方法,您必须使用服务器端语言,并可能添加像数据库这样的存储引擎以使其工作。

I suggest you start here Php for beginnersthe link might be old but it covers all the basics you need to know to create your counter.

我建议你从这里开始PHP 初学者的链接可能很旧,但它涵盖了创建计数器所需的所有基础知识。

回答by James Williams

Javascript cannot change a file on a server or client computer without security issues. You may want to also look into loading another page as a blank image using PHPor another server side script language. That can then update the count on the file with no issues.

如果没有安全问题,Javascript 无法更改服务器或客户端计算机上的文件。您可能还想考虑使用PHP或其他服务器端脚本语言将另一个页面加载为空白图像。然后可以毫无问题地更新文件的计数。

回答by Rayfloyd

Most sites with a counter I see with a lot of traffic use a timed counter and use ajax to get the real number upon load.

我看到的大多数带有计数器的站点都使用定时计数器,并在加载时使用 ajax 获取实际数字。

The benefits of this is you do not have a static counter and you get the real number once you refresh but like it has been said before, with only javascript it is not possible

这样做的好处是你没有静态计数器,刷新后你会得到实数,但就像之前说过的那样,只有 javascript 是不可能的

回答by Anorflame

Javascript is a client side scripting language - it runs on client pc. The counter itself must be implemented at the server side, since you have to count http requests. The javascript code though may request the server to update the counter at the html page displayed at client's pc.

Javascript 是一种客户端脚本语言 - 它在客户端 pc 上运行。计数器本身必须在服务器端实现,因为您必须计算 http 请求。尽管 javascript 代码可能会请求服务器更新客户端 pc 上显示的 html 页面上的计数器。