How to make changes to HTML document permanent using Javascript?

前端 未结 3 1684
误落风尘
误落风尘 2021-01-13 14:16
  1. I have a simple like counter code, but the changes made disappear after the page is refreshed.

  2. Why does this happen, should this be done using PHP ?

3条回答
  •  没有蜡笔的小新
    2021-01-13 15:00

    According to my understanding, you need this count to be global and to be available to all the users who access your page. Javascript is a client side script and the only file you can create using this is a cookie. In this case, you can't use cookies as it is created separately for each user.

    For persistent result use a database or if you are not using a database for your application/website you can use a file (like .txt or .xml) to save your count and next time you can read from that file to display it again. But generally using database is recommended over a file system.

    Using file system:

    For main file we have a small php code to get the existing like count and an ajax function requesting like.php file when a user clicks on the like button.

    HTML body:

    
    Like 
    

    Javascript:

    
    

    In the like.php, we are checking for the post variable "like" just to be sure that we don't simply increment the like on direct access to this file. Here we are checking if the like.txt file exists or not. If true, it gets the first line like=1, get the count, increment the count and return it back to the ajax request. If false, it simply creates the file like.txt with like=1 for the first and only time.

    Hope this is clear enough and helpful for you.

提交回复
热议问题