php - 将 PHP 变量传递给 JavaScript

标签 php javascript

我在将任何类型的变量从 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>

关于php - 将 PHP 变量传递给 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16148772/

相关文章:

php - 更新多行记录

javascript - Highcharts 使用格式化程序更改工具提示日期时间

Php 和 MySQL 使用其他表中的值进行查询

javascript - jQuery 粘性边栏失败 : throws sidebar out of position

javascript - php 的 HTTPRequest 在 firefox 中不返回任何值

javascript - ReactJS 中具有相同 Props 的组件的条件渲染

javascript - html 表中嵌套 ng-repeat

php - 使用 PHP 和 MySQL 的多语言动态内容

php - mysql连接以列出两个表中的项目

javascript - 附加元素未显示 CSS ISSUE JAVASCRIPT PHP