dongyan1841 2016-12-12 00:26
浏览 43
已采纳

将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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'
  • ¥15 vue+element项目中多tag时,切换Tab时iframe套第三方html页面需要实现不刷新
  • ¥50 深度强化学习解决能源调度问题
  • ¥15 一道计算机组成原理问题