문제

I'm trying to pass a php var that is a string using Javascript, but in the final result the string gets cmmented in html. Here's my code:

PHP:

$txtVar = "My text";

JavaScript:

var txt = '<?php echo $txtVar; ?>';
document.getElementById('MyDiv').innerHTML = txt;

HTML(result):

<div id="MyDiv"><!--?php echo $txtVar ; ?--></div>

I just want the string value to be printed in my html, withou the comments ()

도움이 되었습니까?

해결책

First print the PHP variable value in another HTML entity like hidden input HTml tag and after that pick the hidden value using JavaScript and assign into your desire tag.

  1. In Your page.

    <input type="hidden" value="<?php echo $txtVar; ?>" id="phptext" name="phptext" />
    
  2. JavaScript code:

document.getElementById('MyDiv').innerHTML = document.getElementById('phptext').value;

This is works.

다른 팁

Here is your answer.

<?php
$txtVar = "My text";
?>

<div id="MyDiv"></div>

<script>
var txt = "<?php echo $txtVar; ?>";
var element = document.getElementById('MyDiv');
element.innerHTML = txt;
</script>

If your javascript is an external file, you can just rename it with .php extension, and then retrieve it with

<script language='javascript' type='text/javascript' src='yourscript.php'></script>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top