【问题标题】:Json Response needs to update Javascript value and replace global initial global value - work around solution neededJson Response 需要更新 Javascript 值并替换全局初始全局值 - 需要解决解决方案
【发布时间】:2021-03-05 02:28:56
【问题描述】:

我正试图绕开 fetch api 并获取。从我一直在研究的内容来看,它看起来很容易,但我的想法并没有完全理解。在我的游戏 Javascript 中,它以 money=2000 全局变量开头。

游戏运行良好,但是当有人离开并转到他们的个人资料页面并返回游戏时,游戏会重置并从头开始游戏并将钱重置回 2000。

真正疯狂的是,如果我刷新页面,我终于在网页上看到了正确的值 2200,这就是数据库中的值。

startgame.html

<!DOCTYPE html>
<html>
    <head> 
<TITLE>Interactive Game</TITLE>
        <meta charset="UTF-8">
    </head>

    <body background="images/pvpcoinnew.png" style="width=120%" onLoad="updateMoney(); popup('popUpDiv'); click(); updown()" oncontextmenu="return false;">
<img background="images/pvpcoinnew.png">

<select id="textbox">
  <option value="1">1</option>
  <option value="5">5</option>
  <option value="10">10</option>
  <option value="25" selected>25</option>
  <option value="50">50</option>
  <option value="75">75</option>
  <option value="100">100</option>
  <option value="200">200</option>
  <option value="250">250</option>
  <option value="500">500</option>
  <option value="1000">1000</option>
</select> 
    <button type="click" id="button" onclick="enterWager(); return false;">Wager!</button>

    <p>Money: $<span id="money"></span><br></p>


        <script type="text/javascript" src="game.js"></script>

    </body>
</html>

下面的game.js文件一开始就预设了金钱到2000年。 游戏.js

//money = 2000;
window.money = 2000;
          
fetch('../php/moneyupdate/moneyupdate.php?money=value')
  .then((response) => {
    return response.json()
  })
  .then((money) => {
    // Work with JSON data here
    window.money = money
    console.log(money)
  })
  .catch((err) => {
    // Do something for an error here
  })
  
  
document.getElementById("money").innerHTML = window.money;

当从 fetch 触发 php 文件时,状态为 200。XHR 响应负载返回数据库中的“2200”,但网页仍显示 2000。

这里是 moneyupdate.php 文件

<?php 
session_start();
if(empty($_SESSION['userid']))
{
    header("Location: ../login/index.php");
}
include('../../login/database.php');


if(isset($_GET["money"])) {
  $money = htmlspecialchars($_GET["money"]);
  $userid = $_SESSION['userid'];

try {
$db = DB();
$stmt = $db->prepare("SELECT money FROM usersystem WHERE userid=?");
$stmt->execute([$userid]);
$money = $stmt->fetchColumn();


// send a JSON encded money array to client
header('Content-type: application/json;charset=utf-8');
echo json_encode($money);
//}


}
catch(PDOException $e)
{
    $db = null;  
    echo $e->getMessage();  
}
}
// Notes: The json_encode function returns the JSON representation of the given value. 
//        The json_decode takes a JSON encoded string and converts it into a PHP variable.
?>

感谢您的帮助和回复!

【问题讨论】:

    标签: javascript php fetch-api jsonresponse jsonencoder


    【解决方案1】:

    使用 GET['money'] 时,将其添加到您的网址“http:site.com/page.php?money=value”。 window.money = 2000;

    fetch('../php/moneyupdate/moneyupdate.php?money=2000')
      .then((response) => {
        return response.json()
      })
      .then((money) => {
        // Work with JSON data here
         //working with json data depends on structure 
          // you can access data as money.money
        window.money = money
        console.log(money)
      })
      .catch((err) => {
        // Do something for an error here
      })
    

    【讨论】:

    • 好的,这有点帮助。我的网络 XHR 响应中终于有了“2200”。但是页面仍然显示 2000。我需要研究 windows.money 的答案,我认为我的建议不正确。到目前为止谢谢你!!!
    【解决方案2】:

    如果我理解正确,您可能想使用对象窗口来存储您的变量,您可以从任何地方访问它

        window.money = 2000;
        
        fetch('../php/moneyupdate/moneyupdate.php')
          .then((response) => {
            return response.json()
          })
          .then((money) => {
            // Work with JSON data here
            window.money = money
            console.log(money)
          })
          .catch((err) => {
            // Do something for an error here
          })
    

    关于 PHP 部分,我希望能提供帮助,但这不是我的强项。不过,我希望我的提示对您有所帮助。

    【讨论】:

    • 不幸的是,这不起作用。数据库正在显示,以及个人资料页面 2200 钱,但当我从个人资料页面返回游戏时,游戏仍然显示 2000。但是,我将更多地查看窗口,响应负载仍然显示 var money = null;
    • 对不起,我忘了说,这一行也应该使用 window.money 变量: document.getElementById("money").innerHTML = money;你也改了吗?
    • 如果我理解正确,您是说将我的全局更改为 window.money = 2000; ?
    • 好的,我按照您的建议更改了全局。现在有点用了。
    • 我现在想可能是我的 onLoad="updateMoney()
    【解决方案3】:

    已解决 - 起初我不确定将 getElementById 放在哪里,没有意识到它需要在 fetch 中。我还将 fetch 放入一个函数中,以便可以从 html 文件 onload 中调用它,我在 html 页面文件中显示该文件。我还将它插入到 updateMoney() 中。它立即解决了我必须重新加载页面才能看到显示的货币价值的问题。

    game.js

     // window.money = 2000;
        function getMoney(){
        fetch('../php/moneyupdate/moneyupdate.php?money=value')
          .then((response) => {
            return response.json()
          })
          .then((money) => {
            // Work with JSON data here
            window.money = money
            document.getElementById("money").innerHTML = window.money;
            //console.log(money)
          })
          .catch((err) => {
            // Do something for an error here
          })
        }
    
    function updateMoney() {
           if ( pot <= 0 ){ 
           if ( money <= 0 ){ 
           document.getElementById("aaa").innerHTML = "Lost? Here's A Loan !!!";
              money = 1000 ;}
          }
    //       document.getElementById("money").innerHTML = money;
             document.getElementById("money").innerHTML = window.money;
          }
    

    在 JS 中包含上面的代码并不是我需要做的全部。我必须实际触发 getMoney() 以便它获取 php 文件并从数据库中获取列。

    startgame.html

    <body background="images/pvpcoinnew.png" style="width=120%" onLoad="getMoney(); updateMoney(); popup('popUpDiv'); click(); updown()" oncontextmenu="return false;">
    

    我不需要更改 php 页面上的任何内容,但我仍然想知道我是否真的需要这一行,因为我没有将它用于任何事情。 $money = htmlspecialchars($_GET["money"]);

    moneyupdate.php

    <?php 
    session_start();
    if(empty($_SESSION['userid']))
    {
        header("Location: ../login/index.php");
    }
    include('../../login/database.php');
    
    
    if(isset($_GET["money"])) {
      $money = htmlspecialchars($_GET["money"]);
      $userid = $_SESSION['userid'];
    
    try {
    $db = DB();
    $stmt = $db->prepare("SELECT money FROM usersystem WHERE userid=?");
    $stmt->execute([$userid]);
    $money = $stmt->fetchColumn();
    
    
    // send a JSON encded money array to client
    header('Content-type: application/json;charset=utf-8');
    echo json_encode($money);
    //}
    
    
    }
    catch(PDOException $e)
    {
        $db = null;  
        echo $e->getMessage();  
    }
    }
    // Notes: The json_encode function returns the JSON representation of the given value. 
    //        The json_decode takes a JSON encoded string and converts it into a PHP variable.
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-07
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 2014-03-21
      • 2019-09-13
      • 1970-01-01
      相关资源
      最近更新 更多