在Javascript里面回应PHP? [英] Echo PHP inside Javascript?
问题描述
为什么这不起作用?
<?php
mysqli_select_db($connect,"dev");
$response = "Select response from revbut where session='$u'";
$rquery = mysqli_query($connect,$response);
$responseanswer = mysqli_fetch_array($rquery);
$re = $responseanswer['response'];
?>
<script type="text/javascript">
<?php echo $re; ?>
</script>
$ re
里面的JavaScript没有得到回应。但如果我把它放在上面的PHP函数中,它就会得到回应。
$re
inside JavaScript is not getting echoed. But if I place it inside the above PHP function, it is getting echoed.
编辑 - 但是为什么这不起作用?
EDIT - BUT THEN WHY IS THIS NOT WORKING?
if(<?php echo $re; ?>){
document.getElementById('hide').style.display = "none";
}
如果我将隐藏功能置于if之外 - 它正在工作。
if I PLACE the hide function outside the if - it is working.
推荐答案
它得到回应,但你不会在你的页面上看到任何内容,因为文本将写在Javascript标签内,这是浏览器不显示。查看您的页面来源以确认文本确实存在。
It get's echoed, but you won't see anything on your page as the text will be written within the Javascript-tag which is not displayed by the browser. Look at your page source to verify that the text is really there.
编辑
尝试
if(<?php echo json_encode($re); ?>){
document.getElementById('hide').style.display = "none";
}
这将确保您的PHP字符串将转换为适当的Javascript类型 - 如果是字符串,它将确保字符串包含在中并正确转义。
This will ensure that your PHP string will be converted into the appropriate Javascript type - in case of strings it'll ensure that the string is enclosed in "
and is escaped properly.
再次编辑
当您执行以下操作时
<script type="text/javascript">
if(<?php echo $re; ?>){
document.getElementById('hide').style.display = "none"; }
</script>
这是写给HTML的内容页面(然后由浏览器解释)
this is what is written to the HTML page (that's then interpreted by the browser)
<script type="text/javascript">
if(whatever is in the $re vairable){
document.getElementById('hide').style.display = "none"; }
</script>
但这甚至不是有效的Javascript。你想要的是
But this is not even valid Javascript. What you want is
<script type="text/javascript">
if("whatever is in the $re vairable"){
document.getElementById('hide').style.display = "none"; }
</script>
注意确保整个东西是有效的Javascript,并且浏览器的Javascript引擎将
$ re
的内容解释为Javascript字符串。对 json_encode()的调用
正是这样 - 它将PHP变量转换为适当的Javascript变量。
Note the "
which ensures that the whole thing is valid Javascript and that the contents of $re
will be interpreted as an Javascript string by the Browser's Javascript engine. The call to json_encode()
does exactly this - it transforms PHP variables into the appropriate Javascript variables.
这篇关于在Javascript里面回应PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!