如何使用JSON字符串中的数据填充多个html元素?

时间:2017-10-24 20:48:47

标签: html json frontend stringify

以下是我正在使用的代码:

 '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
<script type="text/javascript" src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks-rt.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks-functions.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/hmac-sha256.js'></script>
<script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/parse.js'></script>
</head>
<body>
    <br />
    <br />
    <br />
    <input id="apiKey" type="hidden" value="A319082inSk2"/>
    <input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
    apiCredential<input id="apiCredential"/>
    User Name<input id="username"/>
    Password<input id="password"/>
    <body onload="init()">
    <button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
    <button onClick='gamesparks.authenticationRequest("testuser", "testuser", loginResponse)'>Login</button>
    <button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
    <button onClick='customEvent()'>Custom Event</button>
    <button onClick='testRT()'>Test RT</button>
    <i>Special thanks to the awesome team at GameSparks!</i>
    <div id="messages"></div>
    <br />
    <br />



</body>
    User Name
    <text id="UserName"/>
    <br />
    Coins 
    <text id="Coins"/>
    <br />
    Exp
    <text id="Exp"/>
    <br />
    Leader Points
    <text id="LeadP"/>
    <br />
    Hero Points
    <text id="HeroP"/>


    <div id="UserName" style="color: blue;"></div>
    <div id="Coins" style="color: red;"></div>
    <div id="Exp" style="color: green;"></div>
    <div id="LeadP" style="color: hotpink;"></div>
    <div id="HeroP" style="color: yellow;"></div>

<script type="text/javascript">

    //Create a gamesparks object to be used
    var gamesparks = new GameSparks();

    //Initialse the SDK
    function init() {
        gamesparks.initPreview({
            key: document.getElementById('apiKey').value, 
            secret: document.getElementById('apiSecret').value,
            credential: document.getElementById('apiCredential').value,
            onNonce: onNonce,
            onInit: onInit,
            onMessage: onMessage,
            logger: console.log,
        });
    }

    //Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
    function onNonce(nonce) {
        return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
    }

    //Callback to handle when the SDK is initialised and ready to go
    function onInit() {
        console.log("Initialised");
    }

    //Callback to handle async messages from the gamesparks platform
    function onMessage(message) {
        console.log("onMessage");
    }

    //Response handler examples
    function registerResponse(response) {
        console.log(JSON.stringify(response));
    }

    function loginResponse(response) {
        console.log(JSON.stringify(response));
    }
    function accountDetailsResponse(response) {
        console.log (JSON.stringify(response));//logs the string to console
        document.getElementById("UserName").innerHTML = (response.displayName);
        document.getElementById("Coins").innerHTML = (response.currencies.Coins);
        document.getElementById("Exp").innerHTML = (response.currencies.Exp);
        document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
        document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string.  I've tried doing each line with semicolons at the end, and all in a group with commas separating them.  Both just give me the first variable and delete the rest.
    }


    function customEvent() {
        gamesparks.sendWithData(
            "LogEventRequest", 
            {
                eventKey : "FIRST_EVENT",
                NUMBER_ATTR : 123,
                STRING_ATTR : "this is a string",
                JSON_ATTR : {key1 : 12, key2 : "abc"}
            }, 
            function(response){console.log(JSON.stringify(response));}
        );
    }

    var apiKey = "2974660weiMa";
    var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
    var myTimer = null;
    var myRTSession = function() {};
    var numCycles = 0;

    myRTSession.started = false;
    myRTSession.onPlayerConnectCB = null;
    myRTSession.onPlayerDisconnectCB = null;
    myRTSession.onReadyCB = null;
    myRTSession.onPacketCB = null;
    myRTSession.session = null;

    myRTSession.start = function(connectToken, host, port) {
        var index = host.indexOf(":");
        var theHost;

        if (index > 0) {
            theHost = host.slice(0, index);
        } else {
            theHost = host;
        }

        console.log(theHost + " : " + port);

        myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
        if (myRTSession.session != null) {
            myRTSession.started = true;

            myRTSession.session.start();
        } else {
            myRTSession.started = false;
        }
    };

    myRTSession.stop = function() {
        myRTSession.started = false;

        if (myRTSession.session != null) {
            myRTSession.session.stop();
        }
    };

    myRTSession.log = function(message) {
        var peers = "|";

        for (var k in myRTSession.session.activePeers) { 
            peers = peers + myRTSession.session.activePeers[k] + "|";
        }

        console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
    };

    myRTSession.onPlayerConnect = function(peerId) {
        myRTSession.log(" OnPlayerConnect:" + peerId);

        if (myRTSession.onPlayerConnectCB != null) {
            myRTSession.onPlayerConnectCB(peerId);
        }
    };

    myRTSession.onPlayerDisconnect = function(peerId) {
        myRTSession.log(" OnPlayerDisconnect:" + peerId);

        if (myRTSession.onPlayerDisconnectCB != null) {
            myRTSession.onPlayerDisconnectCB(peerId);
        }
    };

    myRTSession.onReady = function(ready) {
        myRTSession.log(" OnReady:" + ready.toString());

        if (myRTSession.onReadyCB != null) {
            myRTSession.onReadyCB(ready);
        }
    };

    myRTSession.onPacket = function(packet) {
        myRTSession.log(" OnPacket:" + packet.toString());

        if (myRTSession.onPacketCB != null) {
            myRTSession.onPacketCB(packet);
        }
    };

    function testRT() {
        myRTSession.stop();

        gamesparks.initPreview({
            key: apiKey, 
            secret: apiSecret,
            credential: "",
            onNonce: onNonceRT,
            onInit: onInitRT,
            onMessage: onMessageRT,
            logger: console.log,
        });
    }

    function onNonceRT(nonce) {
        return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
    }

    function onInitRT() {
        console.log("Initialised");

        gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function(response) {
            if (response.error) {
                console.error(JSON.stringify(response.error));
            } else {
                sendMatchmakingRequest();
            }
        });
    }

    //Callback to handle async messages from the gamesparks platform
    function onMessageRT(message) {
        //console.log("message " + JSON.stringify(message));
        if (message["@class"] === ".MatchFoundMessage") {
            var accessToken = message["accessToken"];
            var host = message["host"];
            var port = message["port"];

            myRTSession.stop();

            if (myTimer) {
                clearTimeout(myTimer);
            }

            myTimer = setInterval(mainRTLoop, 10);

            myRTSession.start(accessToken, host, port);
        } else if (message["@class"] === ".MatchNotFoundMessage") {
            console.log("MATCH NOT FOUND");

            sendMatchmakingRequest();
        }
    }

    function sendMatchmakingRequest() {
        gamesparks.sendWithData("MatchmakingRequest",
            {
                skill: 1,
                matchShortCode: "Match_STD"
            },
            function(response) {
                if (response.error) {
                    console.error(JSON.stringify(response.error));
                } else {
                    console.log("Match OK...");
                }
            }
        );
    }

    function mainRTLoop() {
        if (myRTSession.started) {
            myRTSession.session.update();

            var data = RTData.get();

            data.setLong(1, numCycles);

            myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);

            numCycles ++;
        }
    }
</script>
</html>'

显然,我试图用字符串中的数据填充一些html元素。问题是,当我使用这个功能时,它只填充第一个元素,并完全从视图中擦除其他元素。所以它返回&#34; testuser&#34; for&#34; UserName&#34;,以及所有其他html元素消失!我希望它显示所有数据!

2 个答案:

答案 0 :(得分:0)

我是否理解正确,只有您的第一个<script> function accountDetailsResponse(response) { console.log(JSON.stringify(response));//logs the string to console document.getElementById("UserName").innerHTML = response.displayName, document.getElementById("Coins").innerHTML = response.currencies.Coins, document.getElementById("Exp").innerHTML = response.currencies.Exp, document.getElementById("LeadP").innerHTML = response.currencies.LeadP, document.getElementById("HeroP").innerHTML = response.currencies.HeroP; } window.onload = function() { response = { displayName: 'A user', currencies: { Coins: 'A coin', Exp: 'A exp', LeadP: 'A lead p', HeroP: 'A hero p', }, }; accountDetailsResponse(response); } </script> <body> <div id="UserName" style="color: blue;"></div> <div id="Coins" style="color: red;"></div> <div id="Exp" style="color: green;"></div> <div id="LeadP" style="color: hotpink;"></div> <div id="HeroP" style="color: yellow;"></div> </body> 正在运作而其他人没有?

非常快速和肮脏但功能正常的例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html"
      xmlns="http://www.w3.org/1999/html">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Insert title here</title>
  <script type="text/javascript"
          src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks-rt.js'></script>
  <script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks.js'></script>
  <script type='text/javascript'
          src='http://martialparks.com/wp-content/themes/blankslate/js/gamesparks-functions.js'></script>
  <script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/hmac-sha256.js'></script>
  <script type='text/javascript' src='http://martialparks.com/wp-content/themes/blankslate/js/parse.js'></script>
</head>
<body onload="init()">
<br/>
<br/>
<br/>
<form>
  <input id="apiKey" type="hidden" value="A319082inSk2"/>
  <input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
  <label for="apiCredential">Api Credential</label><input id="apiCredential"/>
  <label for="username">User Name</label><input id="username"/>
  <label for="password">Password</label><input id="password"/>
  <input type="button" onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)' value="Register" />
  <input type="button" onClick='gamesparks.authenticationRequest("testuser", "testuser", loginResponse)' value="Login" />
  <input type="button" onClick='accountDetailsResponseCreator()' value="Account Details" />
  <input type="button" onClick='customEvent()' value="Custom Event" />
  <input type="button" onClick='testRT()' value="Test RT" />
  <i>Special thanks to the awesome team at GameSparks!</i>
  <div id="messages"></div>
  <br/>
  <br/>
</form>

User Name
<div id="DisplayName" style="color: blue;"></div>
Coins
<div id="Coins" style="color: red;"></div>
Exp
<div id="Exp" style="color: green;"></div>
Leader Points
<div id="LeadP" style="color: hotpink;"></div>
Hero Points
<div id="HeroP" style="color: yellow;"></div>

<script type="text/javascript">

  //Create a gamesparks object to be used
  var gamesparks = new GameSparks();

  //Initialse the SDK
  function init() {
    gamesparks.initPreview({
      key: document.getElementById('apiKey').value,
      secret: document.getElementById('apiSecret').value,
      credential: document.getElementById('apiCredential').value,
      onNonce: onNonce,
      onInit: onInit,
      onMessage: onMessage,
      logger: console.log,
    });
  }

  function accountDetailsResponseCreator() {
    var reponse = {
      displayName: 'A user',
      currencies: {Coins: 'A coin', Exp: 'A exp', LeadP: 'A lead p', HeroP: 'A hero p'}
    }
    accountDetailsResponse(reponse)
  }

  //Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
  function onNonce(nonce) {
    return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
  }

  //Callback to handle when the SDK is initialised and ready to go
  function onInit() {
    console.log("Initialised");
  }

  //Callback to handle async messages from the gamesparks platform
  function onMessage(message) {
    console.log("onMessage");
  }

  //Response handler examples
  function registerResponse(response) {
    console.log(JSON.stringify(response));
  }

  function loginResponse(response) {
    console.log(JSON.stringify(response));
  }

  function accountDetailsResponse(response) {
    console.log(JSON.stringify(response));//logs the string to console
    document.getElementById("DisplayName").innerHTML = (response.displayName);
    document.getElementById("Coins").innerHTML = (response.currencies.Coins);
    document.getElementById("Exp").innerHTML = (response.currencies.Exp);
    document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
    document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string.  I've tried doing each line with semicolons at the end, and all in a group with commas separating them.  Both just give me the first variable and delete the rest.
  }


  function customEvent() {
    gamesparks.sendWithData(
      "LogEventRequest",
      {
        eventKey: "FIRST_EVENT",
        NUMBER_ATTR: 123,
        STRING_ATTR: "this is a string",
        JSON_ATTR: {key1: 12, key2: "abc"}
      },
      function (response) {
        console.log(JSON.stringify(response));
      }
    );
  }

  var apiKey = "2974660weiMa";
  var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
  var myTimer = null;
  var myRTSession = function () {
  };
  var numCycles = 0;

  myRTSession.started = false;
  myRTSession.onPlayerConnectCB = null;
  myRTSession.onPlayerDisconnectCB = null;
  myRTSession.onReadyCB = null;
  myRTSession.onPacketCB = null;
  myRTSession.session = null;

  myRTSession.start = function (connectToken, host, port) {
    var index = host.indexOf(":");
    var theHost;

    if (index > 0) {
      theHost = host.slice(0, index);
    } else {
      theHost = host;
    }

    console.log(theHost + " : " + port);

    myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
    if (myRTSession.session != null) {
      myRTSession.started = true;

      myRTSession.session.start();
    } else {
      myRTSession.started = false;
    }
  };

  myRTSession.stop = function () {
    myRTSession.started = false;

    if (myRTSession.session != null) {
      myRTSession.session.stop();
    }
  };

  myRTSession.log = function (message) {
    var peers = "|";

    for (var k in myRTSession.session.activePeers) {
      peers = peers + myRTSession.session.activePeers[k] + "|";
    }

    console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
  };

  myRTSession.onPlayerConnect = function (peerId) {
    myRTSession.log(" OnPlayerConnect:" + peerId);

    if (myRTSession.onPlayerConnectCB != null) {
      myRTSession.onPlayerConnectCB(peerId);
    }
  };

  myRTSession.onPlayerDisconnect = function (peerId) {
    myRTSession.log(" OnPlayerDisconnect:" + peerId);

    if (myRTSession.onPlayerDisconnectCB != null) {
      myRTSession.onPlayerDisconnectCB(peerId);
    }
  };

  myRTSession.onReady = function (ready) {
    myRTSession.log(" OnReady:" + ready.toString());

    if (myRTSession.onReadyCB != null) {
      myRTSession.onReadyCB(ready);
    }
  };

  myRTSession.onPacket = function (packet) {
    myRTSession.log(" OnPacket:" + packet.toString());

    if (myRTSession.onPacketCB != null) {
      myRTSession.onPacketCB(packet);
    }
  };

  function testRT() {
    myRTSession.stop();

    gamesparks.initPreview({
      key: apiKey,
      secret: apiSecret,
      credential: "",
      onNonce: onNonceRT,
      onInit: onInitRT,
      onMessage: onMessageRT,
      logger: console.log,
    });
  }

  function onNonceRT(nonce) {
    return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
  }

  function onInitRT() {
    console.log("Initialised");

    gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function (response) {
      if (response.error) {
        console.error(JSON.stringify(response.error));
      } else {
        sendMatchmakingRequest();
      }
    });
  }

  //Callback to handle async messages from the gamesparks platform
  function onMessageRT(message) {
    //console.log("message " + JSON.stringify(message));
    if (message["@class"] === ".MatchFoundMessage") {
      var accessToken = message["accessToken"];
      var host = message["host"];
      var port = message["port"];

      myRTSession.stop();

      if (myTimer) {
        clearTimeout(myTimer);
      }

      myTimer = setInterval(mainRTLoop, 10);

      myRTSession.start(accessToken, host, port);
    } else if (message["@class"] === ".MatchNotFoundMessage") {
      console.log("MATCH NOT FOUND");

      sendMatchmakingRequest();
    }
  }

  function sendMatchmakingRequest() {
    gamesparks.sendWithData("MatchmakingRequest",
      {
        skill: 1,
        matchShortCode: "Match_STD"
      },
      function (response) {
        if (response.error) {
          console.error(JSON.stringify(response.error));
        } else {
          console.log("Match OK...");
        }
      }
    );
  }

  function mainRTLoop() {
    if (myRTSession.started) {
      myRTSession.session.update();

      var data = RTData.get();

      data.setLong(1, numCycles);

      myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);

      numCycles++;
    }
  }
</script>
</body>
</html>

什么不起作用?

编辑:

我不确定你在尝试使用Account Detail的东西,但是我以某种方式重写了它,至少innerHTML部分是有效的:

for row in ('*'):
    print(row * userrow)

    for column in ('*'):
        print(column * usercolumn)

希望这有帮助。

答案 1 :(得分:0)

&#13;
&#13;
<?php /**
 * The Header for our theme.
 *
 * Displays all of the <head> section and everything up till <div id="main">
 *
 */ ?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
    <!--<![endif]-->
    <head>
        <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
        <script type="text/javascript"
          src='http://martialparks.com/wp-content/themes/js/gamesparks-rt.js'></script>
        <script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/gamesparks.js'></script>
        <script type='text/javascript'
          src='http://martialparks.com/wp-content/themes/js/gamesparks-functions.js'></script>
        <script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/hmac-sha256.js'></script>
        <script type='text/javascript' src='http://martialparks.com/wp-content/themes/js/parse.js'></script>
        <link rel="profile" href="http://gmpg.org/xfn/11" />
        <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
        <?php
        wp_head();
        ?>
    </head>
    <body <?php body_class() ?>>
        <!--Start Header Wrapper-->
        <div class="header_wrapper">
            <div class="header">
                <!--Start Container-->
                <div class="container_24">
                    <div class="grid_24">
                        <div class="logo"> <a href="<?php echo esc_url(home_url()); ?>"><img src="<?php if (business_directory_get_option('business_directory_logo') != '') { ?><?php echo esc_url(business_directory_get_option('business_directory_logo')); ?><?php
                                } else {
                                    echo esc_url(get_template_directory_uri() . '/images/logo.png');
                                }
                                ?>" alt="<?php bloginfo('name'); ?>" /></a></div>
                    </div>
                    <div class="clear"></div>
                </div>
                <!--End Container-->
                <div class="clear"></div>
            </div>
            <div class="clear"></div>
            <!--Start Menu Wrapper-->
            <div class="menu_wrapper">
                <div class="top_arc"></div>
                <div class="menu-container">
                    <div class="container_24">
                        <div class="grid_24">
                            <?php business_directory_nav(); ?> 
                        </div>
                    </div>
                    <div class="clear"></div>
                </div>
                <div class="clear"></div>
                <div class="bottom_arc"></div>
            </div>
            <!--End Container-->
            <div class="clear"></div>
        </div>
        <!--End Header Wrapper-->
        <div class="clear"></div>
        <div class="wrapper">
            <!--Start Container-->
            <div class="container_24">
                <div class="grid_24">
    <body onload="init()">
<br/>
<br/>
<br/>
<form>
  <input id="apiKey" type="hidden" value="A319082inSk2"/>
  <input id="apiSecret" type="hidden" value="BNuYLYZAoDZDZyh1F7tbR8BMTiqeJbWt"/>
  <label for="apiCredential">Api Credential</label><input id="apiCredential"/>
  <label for="username">User Name</label><input id="username"/>
  <label for="password">Password</label><input id="password"/>
  <button onClick='gamesparks.registrationRequest("testuser", "testuser", "testuser", registerResponse)'>Register</button>
	<button onClick='gamesparks.authenticationRequest("testuser", "testuser", loginResponse)'>Login</button>
	<button onClick='gamesparks.accountDetailsRequest(accountDetailsResponse)'>Account Details</button>
	<button onClick='customEvent()'>Custom Event</button>
	<button onClick='testRT()'>Test RT</button>
  <i>Special thanks to the awesome team at GameSparks!</i>
  <div id="messages"></div>
  <br/>
  <br/>
</form>

User Name
<div id="displayName" style="color: blue;"></div>
Coins
<div id="Coins" style="color: red;"></div>
Exp
<div id="Exp" style="color: green;"></div>
Leader Points
<div id="LeadP" style="color: darkgreen;"></div>
Hero Points
<div id="HeroP" style="color: purple;"></div>

<script type="text/javascript">

  //Create a gamesparks object to be used
  var gamesparks = new GameSparks();

  //Initialse the SDK
  function init() {
    gamesparks.initPreview({
      key: document.getElementById('apiKey').value,
      secret: document.getElementById('apiSecret').value,
      credential: document.getElementById('apiCredential').value,
      onNonce: onNonce,
      onInit: onInit,
      onMessage: onMessage,
      logger: console.log,
    });
  }

  function accountDetailsResponseCreator() {
    var response = {
      displayName: 'A User',
      currencies: {Coins: 'A coin', Exp: 'A exp', LeadP: 'A lead p', HeroP: 'A hero p'}
    }
    accountDetailsResponse(response)
  }

  //Callback function to hmac sha256 a nonce with the secret. It's assumed you will have your own method of securing the secret;
  function onNonce(nonce) {
    return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, document.getElementById('apiSecret').value));
  }

  //Callback to handle when the SDK is initialised and ready to go
  function onInit() {
    console.log("Initialised");
  }

  //Callback to handle async messages from the gamesparks platform
  function onMessage(message) {
    console.log("onMessage");
  }

  //Response handler examples
  function registerResponse(response) {
    console.log(JSON.stringify(response));
  }

  function loginResponse(response) {
    console.log(JSON.stringify(response));
  }

  function accountDetailsResponse(response) {
    console.log (JSON.stringify(response));//logs the string to console
    document.getElementById("displayName").innerHTML = (response.displayName);
    document.getElementById("Coins").innerHTML = (response.currencies.Coins);
    document.getElementById("Exp").innerHTML = (response.currencies.Exp);
    document.getElementById("LeadP").innerHTML = (response.currencies.LeadP);
    document.getElementById("HeroP").innerHTML = (response.currencies.HeroP); //returns value of name from string.  I've tried doing each line with semicolons at the end, and all in a group with commas separating them.  Both just give me the first variable and delete the rest.
  }

  function customEvent() {
    gamesparks.sendWithData(
      "LogEventRequest",
      {
        eventKey: "FIRST_EVENT",
        NUMBER_ATTR: 123,
        STRING_ATTR: "this is a string",
        JSON_ATTR: {key1: 12, key2: "abc"}
      },
      function (response) {
        console.log(JSON.stringify(response));
      }
    );
  }

  var apiKey = "2974660weiMa";
  var apiSecret = "p5pFVnohi5eWPYETb4aPgeMLtd95bjfJ";
  var myTimer = null;
  var myRTSession = function () {
  };
  var numCycles = 0;

  myRTSession.started = false;
  myRTSession.onPlayerConnectCB = null;
  myRTSession.onPlayerDisconnectCB = null;
  myRTSession.onReadyCB = null;
  myRTSession.onPacketCB = null;
  myRTSession.session = null;

  myRTSession.start = function (connectToken, host, port) {
    var index = host.indexOf(":");
    var theHost;

    if (index > 0) {
      theHost = host.slice(0, index);
    } else {
      theHost = host;
    }

    console.log(theHost + " : " + port);

    myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
    if (myRTSession.session != null) {
      myRTSession.started = true;

      myRTSession.session.start();
    } else {
      myRTSession.started = false;
    }
  };

  myRTSession.stop = function () {
    myRTSession.started = false;

    if (myRTSession.session != null) {
      myRTSession.session.stop();
    }
  };

  myRTSession.log = function (message) {
    var peers = "|";

    for (var k in myRTSession.session.activePeers) {
      peers = peers + myRTSession.session.activePeers[k] + "|";
    }

    console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
  };

  myRTSession.onPlayerConnect = function (peerId) {
    myRTSession.log(" OnPlayerConnect:" + peerId);

    if (myRTSession.onPlayerConnectCB != null) {
      myRTSession.onPlayerConnectCB(peerId);
    }
  };

  myRTSession.onPlayerDisconnect = function (peerId) {
    myRTSession.log(" OnPlayerDisconnect:" + peerId);

    if (myRTSession.onPlayerDisconnectCB != null) {
      myRTSession.onPlayerDisconnectCB(peerId);
    }
  };

  myRTSession.onReady = function (ready) {
    myRTSession.log(" OnReady:" + ready.toString());

    if (myRTSession.onReadyCB != null) {
      myRTSession.onReadyCB(ready);
    }
  };

  myRTSession.onPacket = function (packet) {
    myRTSession.log(" OnPacket:" + packet.toString());

    if (myRTSession.onPacketCB != null) {
      myRTSession.onPacketCB(packet);
    }
  };

  function testRT() {
    myRTSession.stop();

    gamesparks.initPreview({
      key: apiKey,
      secret: apiSecret,
      credential: "",
      onNonce: onNonceRT,
      onInit: onInitRT,
      onMessage: onMessageRT,
      logger: console.log,
    });
  }

  function onNonceRT(nonce) {
    return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(nonce, apiSecret));
  }

  function onInitRT() {
    console.log("Initialised");

    gamesparks.deviceAuthenticationRequest((Math.floor(Math.random() * (999 - 1)) + 1).toString(), null, null, "js", null, null, function (response) {
      if (response.error) {
        console.error(JSON.stringify(response.error));
      } else {
        sendMatchmakingRequest();
      }
    });
  }

  //Callback to handle async messages from the gamesparks platform
  function onMessageRT(message) {
    //console.log("message " + JSON.stringify(message));
    if (message["@class"] === ".MatchFoundMessage") {
      var accessToken = message["accessToken"];
      var host = message["host"];
      var port = message["port"];

      myRTSession.stop();

      if (myTimer) {
        clearTimeout(myTimer);
      }

      myTimer = setInterval(mainRTLoop, 10);

      myRTSession.start(accessToken, host, port);
    } else if (message["@class"] === ".MatchNotFoundMessage") {
      console.log("MATCH NOT FOUND");

      sendMatchmakingRequest();
    }
  }

  function sendMatchmakingRequest() {
    gamesparks.sendWithData("MatchmakingRequest",
      {
        skill: 1,
        matchShortCode: "Match_STD"
      },
      function (response) {
        if (response.error) {
          console.error(JSON.stringify(response.error));
        } else {
          console.log("Match OK...");
        }
      }
    );
  }

  function mainRTLoop() {
    if (myRTSession.started) {
      myRTSession.session.update();

      var data = RTData.get();

      data.setLong(1, numCycles);

      myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);

      numCycles++;
    }
  }
</script>
</body>
</html>
&#13;
&#13;
&#13;

WOW!对于一个新的月份编码器来说,这真是一场危机。非常感谢EMAZZOTTA创建了一个代码,它给了我可操作的构建块。同样,如果我提供了所有信息,EMAZZOTTA可以立即修复它。

所以我的代码在几个方面与Zot不同。我不得不纠正一种语法,他们遗漏了对函数的引用&#34; gamesparks&#34;在accountdetailsrequest之前。我还将代码混合了一个新的主题(没有相关性。)我还删除了添加的功能E,填充了&#34; A Coin,A Exp&#34;等等。这是多余的。得到这个的主要原因是:为了填充多个html元素,元素必须正确格式化。 Emazzotta有先见之明