简体   繁体   English

Javascript屏幕宽度/高度到PHP

[英]Javascript screen width/height to PHP

I know it doesn't necessarily make any sense, but is there a way to run javascript on the client, find the screen width/height of the active browser, and then pass those variables to a PHP script? 我知道它没有任何意义,但有没有办法在客户端上运行javascript,找到活动浏览器的屏幕宽度/高度,然后将这些变量传递给PHP脚本?

All the common knowledge is usually PHP >> Javascript, never trust the client I suppose, and I can't find a way at the moment. 所有的常识通常都是PHP >> Javascript,我从不相信客户端,我现在找不到办法。

This is for a .php file, so blocks easily, but I cannot seem to do the reverse. 这是一个.php文件,所以很容易阻塞,但我似乎无法反过来。

I am working on creating a JSON object, but then realized I still have the same wall to climb. 我正在创建一个JSON对象,但后来意识到我还有同样的墙要爬。

Thanks. 谢谢。

I am finding the interactions between technologies somewhat challenging as an amateur, but it makes me feel powerful to know. 我发现技术之间的相互作用作为一个业余爱好者有点挑战,但它让我感到强大。 Maybe soon I'll be able to stop exceptions just with my hands. 也许很快我就能用手停止例外。 Well, the matrix reference fails, because that is what people do on a second tier literal level. 好吧,矩阵引用失败了,因为这是人们在第二层文字级别上所做的事情。

You can do this: 你可以这样做:

<script>
document.getElementById('hidden-field').value = screen.width + ',' + screen.height;
</script>

<input id="hidden-field" name="dimensions" value="" />

and submit the form. 并提交表格。 You could use AJAX to send that data instead, a cookie, an image, etc. I personally would use AJAX. 您可以使用AJAX来发送数据,cookie,图像等。我个人会使用AJAX。

But yes, this is a case where you'll need to just trust the client at face value. 但是,是的,在这种情况下,您需要以面值信任客户。 However, if you are doing something with that data (like creating an image or something) you should still validate that the value makes sense so you don't end up trying to create an image that is 100 million pixels wide, etc. 但是,如果您正在对该数据执行某些操作(例如创建图像或其他内容),您仍应验证该值是否有意义,以便您最终不会尝试创建宽度为1亿像素的图像等。

<script type="text/javascript">
    document.write('<img src="index.php?width='+screen.width+'&height='+screen.height+'"/>');
</script>

(oh lookie here, no AJAX :) ) (哦,看这里,没有AJAX :)

By the way, I highly advice not to use document.write , instead either use window.onload or something better from your preferred JS library (such as jQuery(document).ready(function(){ jQuery(document.body).append("the-image-as-in-my-example"); }) in jQuery). 顺便说一句,我强烈建议不要使用document.write ,而是使用window.onload或更好的首选JS库(例如jQuery(document).ready(function(){ jQuery(document.body).append("the-image-as-in-my-example"); }) jQuery中的jQuery(document).ready(function(){ jQuery(document.body).append("the-image-as-in-my-example"); }) )。

Fast one with jQuery 快速使用jQuery

$(function(){
 $.ajax({
   url: 'file.php',
   type: 'POST',
   data: {h: screen.height, w: screen.width}
 });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM