Javascript变量到php变量转换方法工作.但我无法比较php变量


Javascript variable to php variable conversion method working. But I could not compare that php variable

要将javascript变量发送到php变量,我们必须使用POST或Ajax。

下面的代码将javascript变量转换为php变量,而不使用POST, Get或Ajax方法
当我回显php变量时,它给出了正确的值,所以我假设javascript值被分配给php变量。

但是作为php脚本从服务器端处理,为什么js变量被分配到php变量上的onClick函数?



随它去吧。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>

没有。它不会将PHP变量赋值给从textfield读取的字符串。它只是给它分配了一个文字值"+javavar+",然后显示在JavaScript代码中。所以你实际上是在显示一个名为javavar的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代码吗?

您没有向服务器发送任何数据,并且在您的代码中:

<?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 ...
}
?>