using JS variable in PHP

懵懂的女人 提交于 2021-02-20 04:12:06

问题


how can use JS variable in PHP like this ?

<script>
x = document.getElementById(1).value;
var listOf = <?php echo $listOf[x]; ?>;
</script>

this doesn't work :(


回答1:


And rightfully so. PHP is executed on the server, while JavaScript is executed in the client's browser. Those are two different contexts and the variables from one are not visible in the second.

You need to have your PHP script output a JavaScript version of the array and then use this one in your script. Something like this:

<?php
echo "listArray = new Array();\n";
foreach ($listArray as $key => $value) {
   echo 'listArray[', $key, '] = ', $value, ";\n";
}



回答2:


You can't use it directly like this.

You'll have to use AJAX to send the value from client side to server side and only then PHP can see it.

Using jQuery it can become really simple though:

x = document.getElementById(1).value;
$.get("mypage.php?x=" + x, function(result) {
    alert("response from PHP: " + result);
});

And in the PHP read the x from querystring and send proper output.




回答3:


it is not possible because both are different languages so you cant use javascript varible in php inside javascript




回答4:


This is not possible. PHP is executed serverside, even before its output reaches your browser. JS is executed clientside, in the browser. You can't do this, unless you call some other PHP script with this variable x.




回答5:


You can't. JavaScript is run in your browser while PHP gets run on the server. The only way for JavaScript to communicate with PHP is by using AJAX (XMLHttpRequest), separating the JavaScript from the PHP.




回答6:


like this if you put php in any single or double quotes than it work

<script type='text/javascript'>
x = document.getElementById(1).value;
var listOf = "<?php echo $listOf[x]; ?>";
</script>



回答7:


This will convert javascript variable to php variable.

<script>
function sud(){

javavar=document.getElementById("text").value;  

document.getElementById("rslt").innerHTML="<?php 
$phpvar='"+javavar+"'; 
echo $phpvar.$phpvar;?>";
}

function sud2(){
document.getElementById("rslt2").innerHTML="<?php 
echo $phpvar;?>";
}

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

<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>

</body>

Demo: http://ibence.com/new.php



来源:https://stackoverflow.com/questions/8226915/using-js-variable-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!