简体   繁体   English

PHP中生成的Javascript未执行

[英]Javascript generated in PHP is not executing

I'm trying to create a roulette system, which should work as follows: The user clicks on a submit button, which is then checked on the opening_case_handler.php file to see whether the user has sufficient funds in his account or not, and if he does it will echo javascript code which will create the animation for the roulette and will also come out with the winning prize. 我正在尝试创建轮盘赌系统,该系统应按以下方式工作:用户单击“提交”按钮,然后单击“ opening_case_handler.php”文件以查看用户帐户中是否有足够的资金,以及他这样做会回显javascript代码,这些代码将为轮盘创建动画,并且还会获奖。 For security purposes I am executing the js code in php so the user has no access to it since it is executed in the server side. 为了安全起见,我在php中执行js代码,因此用户无权访问它,因为它是在服务器端执行的。

The issue here is that the js and jquery code do not get executed once this line of code has been reached: 这里的问题是,一旦达到以下代码行,就不会执行js和jquery代码:

var gw = $(".gift").outerWidth(true);

in the opening_case_handler.php . opening_case_handler.php中

You will notice that there are two alerts before and after the previous line code I have just mentioned. 您会注意到,在我刚才提到的上一个代码行之前和之后,有两个警报。 If I uncomment alert("TEST1") it will get executed and an alert message will appear however the rest of the code will no be executed. 如果我取消注释alert(“ TEST1”),它将被执行并显示一条警告消息,但是其余代码将不被执行。 Also if I uncomment only the alert("TEST2") it will not be executed and nothing will happen. 另外,如果我仅取消注释alert(“ TEST2”),它将不会执行,也不会发生任何事情。

To make sure that the javascript code actually works. 确保javascript代码确实有效。 I previously tested it in a javascript file and sourced it in the index.php file and it worked perfectly. 之前,我在javascript文件中对其进行了测试,并在index.php文件中提供了该文件,并且效果很好。

index.php 的index.php

This page contains the roulette with all the different images of each item. 此页面包含轮盘赌,其中包含每个项目的所有不同图像。 The submit button is at the bottom. 提交按钮在底部。 This is the button that users will click to be able to spin the roulette. 这是用户单击以旋转轮盘的按钮。

    <div class='rafflebox'>
      <div class='pointer'></div>
      <div class='boxwrapper'>
        <ul class='giftwrapper'>

          <div class="gift item bg-size2 box-bg3">
              <img class="item-product2" src="graphics/mouse.png" draggable="false">
          </div>

          <div class="gift item bg-size2 box-bg2">
              <img class="item-product2" src="graphics/mouse.png" draggable="false">
          </div>

          <div class="gift item bg-size2 box-bg3">
              <img class="item-product2" src="graphics/mouse.png" draggable="false">
          </div>

          <div class="gift item bg-size2 box-bg4">
              <img class="item-product2" src="graphics/mouse.png" draggable="false">
          </div>


        </ul>
      </div>
    </div>

    <form  method="post">
      <button type="submit" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
    </form>

  </div>

opening_case_handler.php opening_case_handler.php

<?php
session_start ();

if(isset($_POST['opening_case']))
{
 opening_case ();

} 

function opening_case ()

{

if ($_SESSION['balance'] >= $_SESSION['box price'])

  {
    echo '
    <script>
      //alert("TEST1");
      var giftamount = 10;
      var gw = $(".gift").outerWidth(true);
      //alert("TEST2");
      var giftcenter = gw/2;
      var cycle = 7;

      var containercenter = $(".boxwrapper").outerWidth(true)/2;
      for(var i = 0; i <=5; i++)
        {
          var giftduplicate = $(".giftwrapper").children().clone(true,true);
           $(".giftwrapper").append(giftduplicate);
        }

      $(".button").click(function()
      {
            alert("You DO have sufficient funds");
            var btn = $(this);
            btn.hide();
            var randomgift = Math.floor(Math.random() * 4) + 1;
            var dev = Math.random()*(giftcenter+1);
            var distance = giftamount *  cycle * gw   + (randomgift*gw) - containercenter -24 +dev;

            console.log(distance);

            $( ".giftwrapper" ).css({left: "0"});

            $(".giftwrapper").animate({left: "-="+distance},10000,function()
              {
                alert("You Won Gift" + randomgift);
                btn.show();
              });

    });


    </script>';

   } else {

    //to be done

  }
}


?>

Please feel free to express your ideas on how this type of system should be better built. 请随时就如何更好地构建这种类型的系统表达您的想法。 I am open to all suggestions, I am fairly new to this. 我乐于接受所有建议,对此我还很陌生。

Thank you!! 谢谢!!

Try using Heredoc string quoting example for printing your JavaScript: 尝试使用Heredoc字符串引用示例来打印JavaScript:

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

Heredoc text behaves just like a double-quoted string, without the double quotes. Heredoc文本的行为就像带双引号的字符串,没有双引号。 This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. 这意味着heredoc中的引号不需要转义,但是上面列出的转义代码仍然可以使用。 Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings. 变量被扩展,但是在heredoc中使用字符串表示复杂变量时必须同样小心。

If it is just a php code file. 如果只是一个php代码文件。 You can try some below. 您可以在下面尝试一些。

<?php

echo "some stuff here" 

if ($condition){ ?>

<script>
alert("condition true");
</script>

<?php } else { ?>

<script>
alert("condition false");
</script>


<?php }?>

When a form gets submitted it redirects you to the PHP page (ie when you click submit in index.php you will get redirected to opening_case_handler.php ) and then the PHP page will send you back to the index page with the new info. 提交表单后,它会将您重定向到PHP页面(即,当您在index.php中单击Submit时,您将被重定向到Opening_case_handler.php),然后PHP页面会将您发送到带有新信息的索引页面。 Thus, your javascript code gets printed in the opening_case_handler.php which is why your javascript did not get executed. 因此,您的javascript代码会显示在opens_case_handler.php中,这就是为什么您的javascript无法执行的原因。 Also, your javascript code will always be visible unless if you do something really creative so if you are trying to handle any sensitive information do it in PHP or any backend framework you are using. 另外,除非您进行了一些真正有创意的工作,否则您的JavaScript代码将始终可见,因此,如果您尝试处理任何敏感信息,请在PHP或您使用的任何后端框架中进行操作。

There are ways to fix this issue but I would recommend a different approach to solve this issue. 有多种方法可以解决此问题,但我建议您使用其他方法来解决此问题。 You can use an AJAX request which basically works in the following manner: 您可以使用基本上以下列方式工作的AJAX请求:

  1. You send a request to your PHP server with the data you want to send. 您将请求与要发送的数据一起发送到PHP服务器。
  2. Your PHP server will process the request and send it back to you 您的PHP服务器将处理该请求并将其发送回给您
  3. Your Javascript code will process the result and show the animations or whatever you want to do. 您的Javascript代码将处理结果并显示动画或您想要执行的任何操作。

    This way your algorithm is not shown and your client ( the javascript side ) only handles information entered by the user and the results came from the server. 这样就不会显示您的算法,并且您的客户端(在javascript端)仅处理用户输入的信息,并且结果来自服务器。

In your case, we can do that using the following changes 对于您而言,我们可以使用以下更改来做到这一点

Index.php (which can be changed to index.html now) Index.php(现在可以更改为index.html)

  <button type="submit" id="opening_case" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
    $("#opening_case").on("click", ()=>{
        // $.get( "opening_case_handler.php?opening_case=true", function( data ) {
        //     console.log(data.funds)
        // });
        $.ajax({
            url: "opening_case_handler.php?opening_case=true",
            success: (data)=>{
                if(data.funds) {
                    alert("You DO have sufficient funds")
                } else {
                    ("You don't have sufficient funds")
                }
            },
            dataType: "JSON"
        });
    })
</script>

opening_case_handler.php opening_case_handler.php

<?php

if(isset($_GET['opening_case'])) {
   $result = [
      "funds" => true,
   ];
   $ResultsInJSON= json_encode($result);
   echo $ResultsInJSON; 
} 
?>

The index.php will send the request when the button is clicked using AJAX which you can read about it here https://api.jquery.com/jquery.get/ then your PHP will receive the request and response with a JSON code which can be processed using the data.whatever as shown in the example above. 当使用AJAX单击按钮时,index.php将发送请求,您可以在这里https://api.jquery.com/jquery.get/阅读有关该请求的信息,然后您的PHP将接收带有JSON代码的请求和响应。可以使用数据进行处理。无论上面的示例如何显示。

Note: I am not a PHP expert but I believe this will be a better method to use in this case. 注意:我不是PHP专家,但是我相信这是在这种情况下使用的更好方法。

Note2: You don't need Jquery for Ajax but it's easier! 注意2:Ajax不需要Jquery,但是更简单! Here is how you do it without Jquery https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp 这是没有Jquery https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp的情况下的操作方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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