Variable Javascript to PHP int


Variable Javascript to PHP int

我想在php中将Javascript变量转换为INT。

例子:

$res = '<script> var res = Math.max(screen.width,screen.height); document.write(res); </script>';
$int = (int)$res;
var_dump($int);

这段代码返回int(0)或String形式的值,我需要整数形式的正确值。例如1920.

当您使用(int) php尝试将给定字符串转换为整数时,就像它以数字开头一样,它将使用这个数字,例如:

(int) "123cats"; // 123

你怎么没有任何数字在那里php只是给你一个0的结果。你不能以这种方式将javascript变量传递给php脚本。如果你想这样做,你必须传递它在ajax请求或类似的

PHP脚本在服务器端执行,JS在客户端进行解释。在您的示例中,您正在尝试执行back-end中的front-end代码。赋值

$res = '<script> var res = Math.max(screen.width,screen.height); document.write(res); </script>';

server-side中执行,并作为字符串执行。在这种情况下,JS var赋值永远不会发生。这就是它返回0的原因。

您可以执行以下代码

$res = '100<script> var res = Math.max(screen.width,screen.height); document.write(res); </script>'; 

它将返回100。因为int()将从字符串中提取integer