简体   繁体   中英

How to save a Javascript variable as serverside variable so everyone can see it

Hey I have been looking around for like 2 hours now and cant really find what I'm looking for. I want to turn a JavaScript variable into a server-side variable so that when it is changed it is changed for everyone visiting the site. I have tried looking at Node JS, XML, PHP and SQL but i have absolutely no clue which one is the one I need to do this. If any of you guys could give me something to research in order to accomplish this I would be grateful.

My code is a voting function that just increments a variable by 1 and I want it to stay as that variable when refreshed and visited by others.

JS :

/*global*/ buttonText = "Global Clicks: 0";
/*global*/ amountOfvotes = 0;


function addVote() {
  var newButtonText = buttonText.replace("0", amountOfvotes++);
  document.getElementById('global-respects').innerHTML = newButtonText;
}

Thanks!

There are a lot of solutions that you can use for your problem. The first two things which are in my mind are a (1) classic client-server communication, and (2) the usage of web sockets. Well, I am not so firm in the usage of web sockets, so I describe the "easier" client-server communication.

An information before I start: The tools and programming languages are mostly independent. However, you can use JavaScript on the client and PHP on the server side for example.

The first, you need, is a (eg JavaScript) variable on your client. You had called it amountOfVotes (cf. the picture at the end). There are two things happen during the client is active: (1) if the client add a vote it has to send it to the server; (2) all clients have to stay up-to-date .

  1. If the Add Vote button is clicked, then you send a message (eg via Ajax) to your server application. Then, the server takes its current amountOfVotes , adds one vote, and stores it (eg, in a file or mysql database).

  2. Your clients need an intervalled function. This function sends (eg, via Ajax) a message to the server to get the current amountOfVotes . The server's responds with the current number and the client is up-to-date .

消息概述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM