如何使用jQuery或任何其他方法根据浏览器窗口的宽度动态加载不同的PHP文件


how to load a diferrent php file dynamically based on the browser window's width using jQuery or any other method

你好朋友们,一个非常新手的问题,因为我对编程很陌生。

我正在浏览网页,并找到了一种根据浏览器宽度动态加载CSS文件的方法。

jQuery

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $("#size-stylesheet").attr("href", "css/narrow.css");
    } else if ((width >= 701) && (width < 900)) {
        $("#size-stylesheet").attr("href", "css/medium.css");
    } else {
       $("#size-stylesheet").attr("href", "css/wide.css"); 
    }
}
$(function() {
    adjustStyle($(this).width());
    $(window).resize(function() {
        adjustStyle($(this).width());
    });
});

.HTML

<link rel="stylesheet" type="text/css" href="main.css" />
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="narrow.css" />

我想知道,我可以使用相同的工具来加载php file吗?

如果是,代码会是什么样子?

我认为我们将需要使用类似<?php require_once('http://mysite.com/layouts/ipad.php'); ?>的东西,但是我该如何编码呢?

请帮忙。

问候

我想知道,我可以使用相同的方法来加载 php 文件吗?

如果"加载 php 文件"是指加载不同的页面,您将为不同的条件(宽度等(定义不同的页面,那么您可以通过将window.location设置为等于所需的页面来加载不同的页面。这会将当前页面替换为您指定的页面。

不过,我认为您不应该每次调整窗口大小时都这样做。如果您必须这样做,请至少检查新大小是否真的需要更改,而不是无论如何都反复重新加载它。

以下内容类似于现有代码:

function setLocation(url) {
   if (window.location.href.indexOf(url) === -1)
      window.location = url;
}
function reloadPage(width) {
    width = parseInt(width);
    if (width < 701) {
        setLocation("yournarrowpage.php");
    } else if (width < 900) {
        setLocation("yourmediumpage.php");
    } else {
        setLocation("yourwidepage.php");
    }
}
$(function() {
   reloadPage($(this).width());
   $(window).resize(function() {
       reloadPage($(this).width());
   });
});

不过,您不必每次都重新加载整个页面,您可以使用 ajax 仅重新加载某些部分。为此,您可以执行类似于上述操作的操作,除了不使用jQuery的.load() method设置window.location

function setLocation(url) {
   $("selector for the element to reload").load(url);
}

我怀疑您实际上想做的是根据浏览器或分辨率将用户重定向到不同的页面。

$(document).load(function() {
    var $width = $(window).width()
    if($width < 701)
        window.location = 'narrow.php'
    else if($width < 900)
        window.location = 'medium.php'
    else
        window.location = 'wide.php'
})

您可以轻松地使相同的函数在窗口调整大小时运行,尽管在实践中它可能不像您希望的那样工作。

编辑:如果您只是专门为iPad执行此操作(您不应该这样做(:

if(stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla/5.0(iPad;')) {
     // probably an iPad
     require('ipad.php');
     //Or maybe the below might serve you better:
     /*
     header('Location:ipad.php');
     die();
     */
}

这是 css 问题的良好起点:http://topsecretproject.finitestatemachine.com/2009/09/how-to-load-javascript-and-css-dynamically-with-jquery/

有关加载 php,请参阅 使用 javascript 和 jquery 动态包含 php 文件

 if (width < 701) {
    $.get('yourlayoutfor701.php', function(data) {
    $('#your_layout').html(data);  
    });
 }

希望这可能会对您有所帮助,但不是一个好的做法