2013-04-22 295 views
0

我在将任何类型的变量从PHP传递到JavaScript时遇到问题。这是jsFiddle的一个简单例子。为什么它不返回我的字符串?将PHP变量传递给JavaScript

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); 
+0

你缺少链接 – 2013-04-22 13:48:28

+2

你忘了引号:var testvar =“<?php echo $ teststring;?>”;' – x4rf41 2013-04-22 13:50:13

+1

你不能在jsfiddle上测试PHP。 '未捕获的SyntaxError:意外的令牌<' – jbabey 2013-04-22 13:50:48

回答

0

尝试做以下链接:

<?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); 
+0

不起作用。当我把它放在引号中(单或双)时,我回到警报中的是字符串<?php echo $ teststring; ?>不是mystring。 – user2301506 2013-04-22 14:30:48

4

你缺少"

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> 
+0

不起作用。当我把它放在引号中时,我回到警报中的是字符串<?php echo $ teststring; ?>不是mystring。 – user2301506 2013-04-22 14:29:14

+0

@ user2301506我添加了一个演示这个例子。它确实有效。你确定,你正在使用'