将 javascript 值分配给 php 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16007435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:21:33  来源:igfitidea点击:

Assign javascript value to php variable

phpjavascriptjquery

提问by user1889007

I'm trying to check screen width and assign it to a php variable to do some if else statements. This is what I got.

我正在尝试检查屏幕宽度并将其分配给一个 php 变量来执行一些 if else 语句。这就是我得到的。

<script>
    var mobileFormWidthCheck = $(window).width();
    var mobileFormReady;
    if(mobileFormWidthCheck < 767){
        mobileFormReady = 22;
    }
    else{
        mobileFormReady = 55;  
    }

</script>

    <?php   
        $widthChecked = "<script>document.write(mobileFormReady);</script>";
        echo $widthChecked;
    ?>

This works perfectly. But when I try to echo something based on the mobileFormReadyvalue, it doesnt echo.

这完美地工作。但是当我尝试根据mobileFormReady值回显某些内容时,它不会回显。

This is what im trying to get to work.

这就是我试图开始工作的原因。

$widthChecked = "<script>document.write(mobileFormReady);</script>";
if($widthChecked == "22"){
  echo 'this page is under 767 pixels';
}
else if($widthChecked == "55"){
  echo 'this page is OVER 767 pixels';
}
else{
  echo 'NOT WORKING YET';
}

I think its a string integer issue. But I cant seem to figure it out. Can you guys please help me? Thanks a lot.

我认为它是一个字符串整数问题。但我似乎无法弄清楚。你们能帮帮我吗?非常感谢。

回答by Anuj Srivastava

I guess you can use cookies for it.

我想你可以使用cookies。

1) First add a cookie jquery plugin.

1)首先添加一个cookie jquery插件。

2) Then store that window width in a cookie variable.

2) 然后将该窗口宽度存储在 cookie 变量中。

3) Access your cookie in PHP like $_COOKIE['variable name'].(http://www.w3schools.com/php/php_cookies.asp)

3) 在 PHP 中访问您的 cookie,如 $_COOKIE['变量名']。( http://www.w3schools.com/php/php_cookies.asp)

回答by alwaysLearn

You cannot achieve what you want...

你无法达到你想要的...

The reason being

原因是

$widthChecked  is "<script>document.write(mobileFormReady);</script>";
and not 22 or 55.

The reason you are getting the value on echois because it is executing the script and not printing the value of $widhcheck

您获取值的原因echo是因为它正在执行脚本而不是打印$widhcheck