将PHP变量传递给JavaScript

Passing a PHP variable to JavaScript

本文关键字:JavaScript PHP 变量      更新时间:2023-09-26

我有问题传递任何类型的变量从PHP到JavaScript。下面是jsFiddle的一个简单示例。为什么它不返回我的字符串?

http://jsfiddle.net/funinabox/VkNe2/1/

<?php
//create php test string    
$teststring = "mystring"; 
?>

//Convert Php string to JavaScript string
var testvar = <?php echo $teststring; ?> ;
//Display output of the array elements;
alert(testvar);

您缺少"

var testvar = "<?php echo $teststring; ?>";

下面是一个完整的例子

<?php
//create php test string    
$teststring = "mystring"; 
?>

<html>
   <head>
   <script>
   //Convert Php string to JavaScript string
    var testvar = "<?php echo $teststring; ?>" ;
    //Display output of the array elements;
    alert(testvar);
    </script>
    </head>
<body></body>
</html>

我重新安装了xampp,然后在c:'xampp'apache'conf'httpd.conf中添加了1个更改(我在第402行这样做,但在该节中的任何地方都应该是可以的)…AddType application/x-httpd-php .html .htm

现在它工作!!!!!!!!在当前的32位win7 xampp发行版中,这看起来是一个很大的错误。

试着做下面的链接:

<?php
//create php test string    
$teststring = "mystring"; 
?>

//Convert Php string to JavaScript string
var testvar = '<?php echo $teststring; ?>' ;
//Display output of the array elements;
alert(testvar);

我的环境使用模板,所以这不是复制和粘贴代码。然而,我能够通过这样做将变量传递给Javascript:

$teststring = 'mystring'; 
 $page_headers = <<<PAGEHEADERS
 <script>
    window.onload=function(){   
        var testvar = '$teststring';
        alert(testvar);
    };
</script>
PAGEHEADERS;

只要首先定义了php变量,您就应该能够通过调用它来获取值。