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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64