如何在php变量中运行javascript变量值

时间:2018-10-04 10:36:19

标签: javascript php jquery

我正在尝试在PHP变量中设置javascript变量值。但它会显示javascript值。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
  var height = window.screen.availHeight;
  var width = window.screen.availWidth;
</script>
<script>
  document.write(width)
</script>width
<script>
  document.write(height)
</script>

我的代码:-

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
  var height = window.screen.availHeight;
  var width = window.screen.availWidth;
</script>
<?php $height = "<script>document.write(height)</script>"?>
<?php $width = '<script>document.write(width)</script>'?>
<?php echo $width.'width'; echo $height.'height'; echo'<br>'; if($height > '900'){ echo 'Good'; } else { echo 'Bad'; } ?>

它打印的php变量值为width<script>document.write

2 个答案:

答案 0 :(得分:0)

  

您不能将变量值从当前页面的javascript传递到当前页面的PHP代码... PHP代码在服务器端运行,并且对客户端的运行情况一无所知。

这里是完整的解释:https://stackoverflow.com/a/1917626/7182677

答案 1 :(得分:0)

您不能将其传递给PHP,但是可以使用js操作DOM以实现您的目标。只需将if语句移至js文件即可。例如在您的dom中添加元素

 1.ViewModel and View needs to have same name until "View" 
eg: MyView , MyViewModel

 2.You need to load stroryboard name to the Viewcontroller.
 eg:namespace [MvxFromStoryboard("MyView")] 
   public partial class MyView:MvxViewController  where TViewModel :MyViewModel

 3. When loading View, you need to have default constructor. 

   public MyView(IntPtr handle) : base(handle){}

 4.You need to bind viewmodel to the view.Most of the time in ViewDidLoad 
method in ViewClass 

 var set = this.CreateBindingSet<MyView, MyViewModel >();   
 set.Apply();

然后在js

<span id="message"></span>