2017-04-05 126 views
-1

我有一个脚本如下 -如何把一个PHP变量在JavaScript

<script> 
//alert(window.screen.width); 
if (window.screen.width < 250) { 
// resolution is below 10 x 25 
//alert(window.screen.width); 
window.location = 'http://m.xyz.com/'; 
} 
</script> 

我有一个变量在PHP文件如下 -

define("url",  "xyz.com", true); 

我的问题是我怎么能把url作为变量在javascript中

我尝试了以下,但它不工作,并说“网站无法到达”

<script> 
//alert(window.screen.width); 
if (window.screen.width < 250) { 
// resolution is below 10 x 25 
//alert(window.screen.width); 
window.location = 'http://m.<?php echo $url ?>'; 
} 
</script> 
+0

1.你确定define语句包含在你的文件中。 2.网址有效。 3. $ url需要用url(定义的值不是变量)替换。 – jeff

+0

@jeff 1.是的,define语句包含在一个单独的php文件中,php文件包含在文件2中。2.是,url有效3.如果我用url替换$ url,它不起作用 – user20152015

+0

它不起作用不是一个有用的评论。什么/没有发生?控制台告诉你什么? – jeff

回答

1

请像这样写入你的PHP文件,我试过下面的代码,它对我来说工作得很好:

<?php define("url","xyz.com", true); ?> 


<script> 
//alert(window.screen.width); 
if (window.screen.width < 250) { 
// resolution is below 10 x 25 
//alert(window.screen.width); 
window.location = 'http://m.<?php echo url ?>'; 
} 
</script> 
+0

谢谢@Ajay Malhotra – user20152015

0

只需更换:

<?php echo $url ?> 

由:

<?= $url ?> 
0

常量不需要使用$所以只是使用像

<?=url?> 

,将工作

相关问题