Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

javascript - PHP, JS View Counter and Save

I try to make a view counter in js for my webpage.

When you view the page, the counter will increase with 1.

The counted numbers are displayed.

But one thing is not working: When I view the website from another device, the counter starts at 0.

So I used localStorage to store the data. But I want when I see the page from my laptop, the counter increases by one. And when I view the page from my phone the counter should already show the number one and should increase it with one ,so the counter will be 2.

I don't know how to make it workable. It's only done with LocalStorage. I thought I should save the data, by storing the data in a .txt file, but it does not work because when the filewriter save the datas (1) into the file, it will save the next view (1) next to the previous number. And if I want to add the current number to the previous it will show number 1.

Here's my code:

var n = localStorage.getItem('profile_1_tech.html');

if (n === null) {
  n = 0;
}

n++;

localStorage.setItem("profile_1_tech.html", n);

document.getElementById('counter').innerHTML = n;
<span><span id="counter"></span> Views</span>
question from:https://stackoverflow.com/questions/65559817/php-js-view-counter-and-save

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The JavaScript LocalStorage API is only meant to be used on one device, and using the SessionStorage API would be of even less use because that memory is cleared as soon as the tab is closed.

As your question tag has PHP included what you can do is create an account system that increments a value that you would store in a SQL table using PHP, and every time a user creates an account you would create a new "views" field just for them.

However if you are trying to use a view counter for analytical purposes to see how many people use your website then I can suggest using Google Analytics because it is free and requires very minimal code as opposed to my aforementioned "account system" approach with storing the views in a database with PHP.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...