获取PHP变量的javascript变量

时间:2017-02-28 12:49:11

标签: javascript php mysql

我有一个代码,我必须将PHP变量放在JS中,并以其他方式放在同一个文件中。

从PHP到JS都没有问题,但从JS到PHP有点困难。

也许你可以提供帮助。

<?php 
 if($freischaltung==1){
?>
<tr><th><a type="button" name="msg" href="Nachrichten.php?ID=<?php echo $id; ?>">Nachricht senden</a></th></tr> 
<tr><th>
<?php 
  } else {
?>
<button onclick="freischalten()">Freischalten</button>
<p id="FreischaltungAusgabe"></p>
<?php
   echo "<script>
    var krone =".$kronen.";
   </script>";
?>          
<script>
  function freischalten() {
    var x;
    if (confirm("Das Freischalten kostet dich 2 Kronen!") == true) {
        krone = krone -2;
        if(krone<2){
          x = "Du hast zu wenige Kronen um eine Freischaltung durchzuführen!";
         document.getElementById("FreischaltungAusgabe").innerHTML = x;
        } else {
         x = "Erfolgreich freigeschaltet! Restliche Kronen = "+krone;
         $freischalten = 1; // This should be a PHP Variable
         //Also I want to do at this part a INSERT INTO friends Where....
        document.getElementById("FreischaltungAusgabe").innerHTML = x;
      }
    } else {
     x = "Vielleicht beim nächsten mal!";
     document.getElementById("FreischaltungAusgabe").innerHTML = x;
    }
}
</script>
   

我希望将$ freischalten变量作为JS之外的PHP变量。我也想把它插入这个部分的表格中。

2 个答案:

答案 0 :(得分:0)

JS是一种客户端语言,PHP是服务器端语言。您不能将JS变量直接设置为PHP变量。使用隐藏表单或Ajax在PHP变量中获取JS变量。

答案 1 :(得分:0)

我很确定你想要做什么是可能的,但你必须重新加载页面,要么使用ajax调用刷新角色页面。

默认情况下,网页是静态的,浏览器加载页面后按原样显示,你可以激活javascript和其他东西,但要将JS变量解析为PHP,你必须提交表单或使用Ajax调用另一个php脚本并将结果返回到当前页面。

根据w3schools

AJAX是开发人员的梦想,因为你可以:

  • 更新网页而不重新加载页面
  • 在页面加载后从服务器请求数据
  • 在页面加载后从服务器接收数据
  • 将数据发送到服务器 - 在后台

你应该用你的主要php形式做这样的事情:

function parseVariable() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     // the element this.responseText will be all the content returned by your php script called by the xhttp.open
     document.getElementById("myelement").innerHTML = this.responseText;
    }
  };
  // the method can be either GET or POST
  xhttp.open("GET", "myphpscript.php?myvariable=" + document.getElementById("myfield").value , true);
  xhttp.send();
}

之后,您必须使用javascript调用HTML中的parseVariable()函数。

<input type="text" name="myfield" id="myfield">
<button type="button" onclick="parseVariable()">Parse</button>
<p id="myelement">&nbsp;</p>

myphpscript.php中,您将作为GET方法处理呼叫以接收“myfield”文本内容,执行您需要执行的操作并将结果回显到主页面。假设您将收到变量并向其添加10并将其返回主页面。

<?php 

$result = $_GET["myvariable"]; //GET the JAVASCRIPT variable into PHP
$result = $result + 10;
echo $result; 
?>