繁体   English   中英

将Javascript变量转换为PHP会话变量,然后通过Ajax对其进行多次使用

[英]Javascript Variable to PHP Session Variable and then call it via Ajax for multiple use

我正在尝试服务器设备的特定布局以及基于浏览器视口的内容。 我的网站很繁琐,出于某些特定原因,主要是页面加载速度,因此我不使用媒体查询。 我只需要以这种方式完成这项任务。

好的,情况是这样的.....

我有2个文件index.phpviewport.php都位于文件夹http://localhost/test/

为了获得浏览器视口并将值转换为PHP变量,我使用以下脚本:

<?php
if (isset($_GET['width'])) {
  $layoutType = $_GET['width'];

      if ( $layoutType >= 240 && $layoutType <= 600 ) {
        $layoutType = 'mobile';
      } else if ($layoutType >= 601 && $layoutType <= 900 ) {
          $layoutType = 'tablet';
      } else {
         $layoutType = 'desktop';
      }
} else {
  echo "<script language='javascript'>\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width=\" + document.documentElement.clientWidth;\n";
  echo "</script>\n";
  exit();
}
?>

我的问题:

Q1。 如何将$layoutType存储为会话变量,以便可以多次使用它? 正确的语法是什么?

Q2。 我如何从index.php运行文件viewport.php并仅获取$layoutType而没有其他数据。 这是因为通过使用<?php require_once ?>方法,我得到的URL是这样的: http://localhost/test/index.php?&width=1600 我希望URL仅显示为http://localhost/test/ 我需要在index.php文件中使用的正确语法是什么?

Q3。 跳过Ajax部分是否有办法摆脱URL的index.php?&width=1600 我尝试通过.htaccess尝试,但出现错误消息: “页面未正确重定向”

请注意:我不打算使用jQuery和MooTools之类的JavaScript库,因为这是我整个网站中唯一的JavaScript函数,因此无法为其加载整个库。

首先,PHP发生在服务器端,因此,一旦页面加载,再次使用PHP(不加载页面)的唯一方法就是进行ajax调用,可能是调用另一个执行特定功能并返回值的php页面。

如果要将值存储为会话变量以便可以连续使用,则可以执行以下操作:

  1. 当他们第一次登陆您的网站时,请使用php检查会话是否存在,如果不存在,请调用Javascript函数以获取layoutWidth并对将其存储为会话变量的php页面进行ajax调用,然后重新加载页面并包含正确的布局文件。

我可能不会使用此方法,而是实际使用JavaScript / JQuery来研究此方法。 但这就是您要这样做的方式。

对于您的示例,我根本没有使用过JQuery,但是我希望include大约只有19kb左右,它使工作变得非常轻松。

例:

index.php

<?php
   session_start();
?>
<!DOCTYPE html>
<html>
   <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <?php 
         if (empty($_SESSION['layoutWidth'])) {
            echo '<script type="text/javascript"> var session=false; var layoutWidth;</script>';
         } else {
            echo '<script type="text/javascript"> var session=true; var layoutWidth=' . $_SESSION['layoutWidth'] . ';</script>';
         }
      ?>
      <script type="text/javascript" src="js/viewport.js"></script>
   </head>
   <body>
         <?php

            if (!empty($_SESSION['layoutWidth'])) {
               $layoutWidth = $_SESSION['layoutWidth'];
               if ( $layoutWidth >= 240 && $layoutWidth <= 900 ) {
                  include('layout1.php');
               } else if ($layoutWidth > 900 && $layoutWidth <= 1200 ) {
                  include('layout2.php');
               } else {
                  include('layout3.php');
               }
            }
         ?>
   </body>
</html>

js / viewport.js

// JavaScript Document

window.onload = function() {
    // if there is no session (session = false)
    if (!session) {
        // call function to get the screen size
        getScreenWidth();

        // make ajax call to php page to set the session variable
        setSession();
    }
}

function getScreenWidth() {
    layoutWidth = screen.width;
}

function setSession() {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        // Reload the page
        window.location.reload();
        }
      }
    xmlhttp.open("POST","set_session.php?layoutWidth=" + layoutWidth,true);
    xmlhttp.send();
}

您的php文件以设置会话,该参数是通过ajax调用传递的:

set_session.php

<?php
    session_start();
    // you can check if it is already set if you like otherwise:
    $_SESSION['layoutWidth'] = $_REQUEST['layoutWidth'];
?>

layout1.php

<?php
   echo '<div>This is layout1.php</div>';
   echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>

layout2.php

<?php
  echo '<div>This is layout2.php</div>';
  echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>

layout3.php

<?php
   echo '<div>This is layout3.php</div>';
   echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>

这种方法意味着您不必在URL中传递参数。 它将全部隐藏。

Q1)$ _SESSION ['layoutType'] = $ layoutType;

Q2&Q3)我认为您对自己来说太复杂了。 实现您想要的限制的最佳方法是将Cookie和会话的功能结合在一起,您将获得更快,更整洁的代码。 因此,您可以做的是检查是否设置了会话layoutType,如果没有设置,请注入一个JavaScript代码,该代码将为您获取layoutType并将其放入Cookie中,然后在您下次在一个页面中包含viewport.php时,它就可以了。 ll检查是否设置了cookie,并将其传输到会话中以备将来使用,因此您可以将viewport.php更改为:

<?php
  if(isset($_SESSION['layoutType'])){
    //write the code for when session is set here
  }elseif(isset($_COOKIE["layoutType "])){
    $_SESSION['layoutType']=$_COOKIE["layoutType "];
  }else{
      $script = "<script language='javascript'>function SetCookie(cookieName,cookieValue) { var today = new Date(), expire = new Date(), nDays=1;expire.setTime(today.getTime() + 3600000*24*nDays);document.cookie = cookieName+'='+escape(cookieValue)+ ';expires='+expire.toGMTString();SetCookie('layoutType',document.documentElement.clientWidth}";
      echo $script;
  }
?>

暂无
暂无

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

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