-->

Echo PHP inside Javascript?

2020-08-25 05:14发布

问题:

Why is this not working?

<?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 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 I PLACE the hide function outside the if - it is working.

回答1:

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.

EDIT

Try

if(<?php echo json_encode($re); ?>){
    document.getElementById('hide').style.display = "none"; 
}

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.

EDIT again

When you do the following

<script type="text/javascript"> 
if(<?php echo $re; ?>){
    document.getElementById('hide').style.display = "none"; } 
</script>

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>

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>

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.



回答2:

try this:

<script type="text/javascript">
alert('<?php echo $re; ?>');
</script>


回答3:

First, you cannot assume that all DB related operations will always complete sucesfully and will always return data. Open the PHP manual, review all your mysqli_* function calls and add a proper test to detect whether they return an error code or not.

Second, PHP and JavaScript don't run at the same time. After PHP is done all you get is some plain text that's sent to the browser. If that text happens to be JavaScript code, it will be run. And you don't have to guess: the JavaScript code is right there and you can use your browser's View Source menu to inspect it.



回答4:

do view source it is echoing try it and confirm

<script type="text/javascript">
alert('<?=$re; ?>');
</script>