dongyan1841
2016-12-12 00:26
浏览 41

将php变量传递给另一个文件中的javascript

I'm having problems with passing php variables to javascript. It does pass through the variable that is declared at the top, but I don't know how to call the function to get the new version of variable after the IF statement is done.

$info = "A message";

if (true){

    $info = 'Message to be passed';


}

The script that is used to pass the php variable to javascript file:

<script type='text/javascript'> 
var info = "<?php echo $info; ?>";
</script> 

I was wondering what could I do to fix this problem?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsh125986083 2016-12-12 00:57
    已采纳

    The simple way (this requires both files to be PHP files):

    <?php
    
    require_once "your_php_file_here.php"; // Change to your PHP file here
    
    ?>
    
    <script type='text/javascript'>
    
    var info = "<?php echo $info; ?>";
    alert(info);
    
    </script>
    

    This will only allow you to get the value on page load. You need to reload the page if you want it to get a new value.

    The (in my opinion) better way (the file can be HTML) using Ajax:

    <script type='text/javascript'>
    
    var info;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'your_php_file_here.php'); // Change to your PHP file here
    xhr.onload = function() {
        if (xhr.status === 200) {
            info = xhr.responseText;
            alert(info);
        } else {
            alert('Request failed: ' + xhr.status);
        }
    };
    xhr.send();
    
    </script>
    

    This can be put in a function and called as many times as you want. It can get the new value without the need to reload the page.

    For this to work, you need to change your PHP code to:

    $info = "A message";
    
    if (true){
    
        $info = 'Message to be passed';
    
    }
    
    echo $info;
    

    I did not add support for IE6 and below because I think it's about time we stop supporting browsers that lost support by their developers many years ago.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题