如何根据屏幕分辨率或大小执行php文件

时间:2015-11-25 16:05:13

标签: javascript php jquery html ajax

我有2个php文件。

include_once('medium.php');
include_once('mobile.php');

我希望在屏幕尺寸为> 992px时执行medium.php文件,如果屏幕尺寸为< 924px则执行mobile.php 992px

到目前为止我尝试的是:

<script>
var width = $(window).width();
if (width > 992){
</script>   
include_once('medium.php');
<script>} else{</script>
include_once('mobile.php');
<script>}</script>

但无法得到结果。

3 个答案:

答案 0 :(得分:0)

使用jquery和ajax $.load()函数

var width = $(window).width();
if (width > 992){
  $( "body" ).load( "medium.php" );
} else{
$( "body" ).load( "mobile.php" );
}

答案 1 :(得分:0)

您应该使用Ajax或Http.get将宽度屏幕显示为PHP文件,并让php处理执行

<?php
if(isset($_GET['size']) && $_GET['size'] > 992) {
    include_once('medium.php');
} else {
    include_once('mobile.php');
} ?>

答案 2 :(得分:0)

使用jQuery.load()jQuery.post()jQuery.get()jQuery.ajax()

<script type="text/javascript">
var script = window.innerWidth > 992 ? "medium.php" : "mobile.php";
var postVars = {} // Use this to provide additional data to you PHP script, or ommit this parameter if you don't need it
var dataType = 'json'; // The type of data your PHP script will return, could be html, json, text. ommit this if you don't have a particular use for it.

jQuery.post(script, postVars, function(response) {
    // This is your callback function, you can do whatever you please with response here.
}, dataType)
</script>

安全通知 永远不要相信最终用户!由于这是客户端脚本,因此这些变量可以操作为config.php。

要解决此问题,您应该代替请求多个脚本,请求单个脚本,提供包含文件的参数,然后检查是否允许包含该文件。

<script type="text/javascript">
var script = window.innerWidth > 992 ? "medium.php" : "mobile.php";
var postVars = {file_to_include: script}
var dataType = 'json'; // The type of data your PHP script will return, could be html, json, text. ommit this if you don't have a particular use for it.

jQuery.post("include.php", postVars, function(response) {
    // This is your callback function, you can do whatever you please with response here.
}, dataType)
</script>

然后在PHP脚本中

<?php
    if(in_array($_POST["file_to_include"], array("medium.php", "mobile.php"))) {
        include $_POST["file_to_include"];
    }
?>