0

我有一个选项供用户在登录系统时选择他/她自己的主题,并且该主题设置在 MYSQL 数据库中并在每次用户登录时调用,这由以下方式调用:

<?php $_SESSION['SESS_THEME_NAME']; ?>

现在,我在一个 PHP 文件中工作,但不幸的是我需要它在 Javascript 中工作。我需要一些帮助。我使用 Google Chrome 上的开发人员工具查看了代码,看起来上面的代码没有在 javascript 文件中解析。这是有道理的,因为您无法访问 javascript 文件中的会话变量(正如我通过搜索 Google 发现的那样。)

该代码基本上应该根据从 MYSQL 数据库中提取的值设置特定的样式表。因此,如果数据库说Default脚本需要告诉网页使用该default.css文件。等等等等。

我写这篇文章的尝试如下:

var themName="<?php $_SESSION['SESS_THEME_NAME']; ?>";

if (themeName == "Default") 
{
    document.write("<link re='stylesheet' type='text/css' href='css/mws-theme.css'>");
};
if (themeName == "Army")
{
    document.write("<link rel='stylesheet' type='text/css' href='css/mws-theme-army.css'>");
};
if (themeName == "Rocky Mountains")
{
    document.write("<link rel='stylesheet' type='text/css' href='css/mws-theme-rocky.css'>");
};
if (themeName == "Chinese Temple")
{
    document.write("<link rel='stylesheet' type='text/css' href='css/mws-theme-chinese.css'>");
};
if (themeName == "Boutique")
{
    document.write("<link rel='stylesheet' type='text/css' href='css/mws-theme-boutique.css'>");
};
if (themeName == "Toxic")
{
    document.write("<link rel='stylesheet' type='text/css' href='css/mws-theme-toxic.css'>");
};
if (themeName == "Aquamarine")
{
    document.write("<link rel='stylesheet' type='text/css' href='css/mws-theme-aquamarine.css'>");
};

任何一次的帮助都会很棒,非常感谢!我快到最后期限了:/

4

2 回答 2

3

我认为你让这种方式太复杂了。为什么不直接使用 PHP 写出<link>标签呢?

$themes = array(
  'Default' => '',
  'Army' => '-army',
  'Rocky Mountains' => '-rocky'
  // etc...
);

echo "<link rel='stylesheet' type='text/css' href='css/mws-theme-{$themes[$_SESSION['SESS_THEME_NAME']]}.css'>";
于 2013-06-26T04:16:56.710 回答
1

"Now, I had this working in a PHP file but I need it to work in Javascript instead unfortunately. And I need some help. I looked at the code using the developers tools on Google Chrome and looks like the above code is not resolving within the javascript file. Which makes sense because you can't access session variables within a javascript file (as I found by searching Google.)"

Sure you can. Name your javascript file foo.php.

Inside, you can use PHP:

<?php
header('Content-type: application/x-javascript');
session_start();
?>
var theme_name = "<?php echo $_SESSION['SESS_THEME_NAME']; ?>";
...
于 2013-06-26T04:22:12.860 回答