2013-03-15 57 views
-3

要將javascript變量發送到php變量,我們必須使用POST或Ajax。

下面代碼轉換JavaScript變量PHP變量而不使用POST,獲取或Ajax的方法
當我回聲PHP變量它給出了適當的值,所以我假定的JavaScript值被分配給PHP變量。

但是,由於php腳本從服務器端進程,爲什麼js變量被分配給onClick函數上的php變量?Javascript變量到php變量轉換方法的工作。但是我無法比較那個php變量



讓它成爲。 Js變量現在分配給了php變量。並顯示出適當的價值。 但爲什麼比較PHP變量不工作?

演示:http://ibence.com/jstophp.php

<script> 
function jstophp(){ 

var javavar=document.getElementById("text").value; 
document.getElementById("rslt").innerHTML="<?php 

$phpvar='"+javavar+"'; 
echo 'Converted from js variable to php variable:'.$phpvar; 


if($phpvar=='a'){ 
    echo '<br>You have typed letter a'; 
} 

else{ 
    echo '<br>If you have not typed letter a, this program is working according to logic. but if you have entered letter a, why this message is displaying?'; 
} 

?>"; 
} 

</script> 
<body> 

<div id="rslt"></div> 

<input type="text" id="text" /> 
<button onClick="jstophp()" >Convert js to php</button> 

</body> 
+0

JavaScript和PHP是分離的,並沒有什麼可以做的。 – 2013-03-15 23:40:36

回答

3

不,它不需要。它不會將一個PHP變量分配給從文本字段讀取的字符串。它只是給它分配一個文字值"+javavar+"然後顯示到你的JavaScript代碼中。所以你實際上顯示了一個叫做​​的JavaScript變量。

見你的腳本看起來像PHP處理後:

<script> 
function jstophp(){ 

var javavar=document.getElementById("text").value; 
document.getElementById("rslt").innerHTML="Converted from js variable to php variable:"+javavar+"<br>If you have not typed letter a, this program is working according to logic. but if you have entered letter a, why this message is displaying?"; 
} 

</script> 

你能看到字符串"+javavar+"如何得到嵌入有創建工作的JavaScript代碼?

+0

太好了!... 感謝您解決這個問題.... – 2013-03-15 23:46:25

1

你沒有任何數據發送到服務器,並在代碼:

<?php 
$phpvar='"+javavar+"'; // assigning "+javavar+" to $phpvar which stays like that 
if($phpvar=='a'){ // which is not true since $phpvar= "+javavar+" ! 
    echo '<br>You have typed letter a'; 
}else{ 
// your message ... 
} 

?>