简体   繁体   中英

How do I update javascript variables with new values which are changing in my database?

I'm building a multiplayer game which uses a mysql database to store coordinate positions of players, which are then used to display opponent models.

The game uses a javascript file (milktruck.js) on the client side, and then a php file (xml_http_request.php) on the server side.

My problem occurs when trying to get the javascript variables (which store the coordinate information of an opponent) updated as the database information is updated.

The javascript variables are declared within the php file with the following code:

  echo "<script> var lla0php = $lla0; </script>";
  echo "<script> var lla1php = $lla1; </script>";
  echo "<script> var lla2php = $lla2; </script>";

Then used in the javascript file, ticking function: prototype.tick, with:

  window['lla0_2']= lla0php;
  window['lla1_2']= lla1php;
  window['lla2_2']= lla2php;

How do I continuously update these variables with new database information?

The web model is stateless, and to do this you're going to have to think of a way to overcome this and may possibly consider writing an abstraction layer that takes care of this for you.

You'll either need to poll continuously or look into other web-based solutions that allow the server to "push" data back to the client and maintain an "open channel" of communication. An example of this would be Google Talk in your browser or FaceBook chat.

What you need to do is use ajax.


function requestCoord(){
    $.ajax({
        url: "your url",
        dataType : "json",
        type: "GET",
        success(val){
            //get your php script to echo out a json string 
                        //and it will be in val
            window['lla0_2']= val.lla0php;
            window['lla1_2']= val.lla1php;
            window['lla2_2']= val.lla2php;

        }
    });
}

setInterval(requestCoord, 1000);

UPDATE

You can use html5 sockets.

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