2017-02-28 89 views
1

我有一個代碼,我必須把PHP變量放在JS和其他方式在同一個文件中。獲取一個JavaScript變量到PHP變量

從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變量。另外我想將它插入此部分的表格中。

+0

您的設計基本上是錯誤的。當你需要像這樣混合JS和PHP時,你應該回到繪圖表並重新思考你在做什麼。也許,你應該做的是保持js(不,你應該確保你的js在一個單獨的外部文件中,並捕獲js中的點擊/事件,而不是使用onclick和類似的東西),並使用AJAX向/從PHP發送/接收信息。 – junkfoodjunkie

+0

你可以通過ajax保存值並保存到會話中,或者嘗試保存它的cookie – Mohammad

+0

你應該通過ajax將值發送到正確的php代碼文件 – scaisEdge

回答

0

JS是客戶端語言,PHP是服務器端語言。你不能直接將JS變量設置爲PHP變量。使用隱藏表單或Ajax來獲取PHP變量中的JS變量。

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(); 
} 

之後,你必須調用parseVariable()功能在你的HTML,使用JavaScript。

<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; 
?>