在链接点击时运行PHP脚本而不刷新页面

时间:2012-11-11 16:43:15

标签: php javascript jquery styleswitching

好的,所以我在php中完成了一个样式切换器,我将它用作我网站上的一个隐藏功能,当用户键入“teema”时会触发该功能,并且会在顶部显示一个模式框页面内容并显示可用的主题。

<ul>
    <li><a href="teema.php?teema=default" class="ajaxLink">Normaali</a></li>
    <li><a href="teema.php?teema=superhero" class="ajaxLink">Superhero</a></li>
    <li><a href="teema.php?teema=spacelab" class="ajaxLink">Spacelab</a></li>
    <li><a href="teema.php?teema=united" class="ajaxLink">United</a></li>
    <li><a href="teema.php?teema=cyborg" class="ajaxLink">Cyborg</a></li>
</ul>

但是,我想在没有页面刷新的情况下更改主题,因此css应该在后台加载。这是teema.php:

<?php
    $style = $_GET['teema'];
    setcookie("teema", $style, time()+604800);
    if(isset($_GET['js'])) {
        echo $style; 
    } 
    else{
    header("Location: ".$_SERVER['HTTP_REFERER']);  
    }
?>

检查cookie的索引上的php:

<?php 
if(!empty($_COOKIE['teema'])) $style = $_COOKIE['teema'];
else $style = 'default';
?>
<link rel="stylesheet" href="css/<? echo $style;?>.css" id="theme">

如何在后台加载新的css,并使用jQuery将其淡化为旧的CSS?

3 个答案:

答案 0 :(得分:1)

您可以在PHP文件中提供JavaScript内容类型的响应并操作样式表。

以这种方式更改代码:

<?php
    $style = $_GET['teema'];
    setcookie("teema", $style, time()+604800);
    if(isset($_GET['js'])) {
        // echo $style; 
    } 
    else{
     // header("Location: ".$_SERVER['HTTP_REFERER']);  
    }
    header("Content-type: text/javascript");
?>
document.getElementById("theme").setAttribute("href", "teema.css");

使用AJAX和PHP更改主题。

由于您已经在id="theme"标记中使用了<link />,因此我们可以使用AJAX轻松地在jQuery中设置内容。

所以,你这样给出一个主题请求:

$.getScript("theme.php?teema=theme");

在PHP中:

header("Content-type: text/javascript");
$('#theme').attr('href', 'css/<?php echo $_GET['teema']; ?>');

答案 1 :(得分:1)

更改此链接的内容($('$#theme').attr('href', 'css/' + selectedtheme +'.css');,您也可以在javascript中设置Cookie(document.cookie = 'theme=' + selectedtheme

答案 2 :(得分:1)

您可以简单地发出ajax请求,以便返回cookie

使用jQuery:

$('.ajaxLink').click(function(e) {
    e.preventDefault();
    var teemaUrl=this.href;
    var teema=teemaUrl.split('=').pop()
    $.get(teemaUrl, { js:true}, function(data){
       $('#theme').attr('href','css/'+ teema+'.css')

    })
});

这将解析链接teema中的href值,调用href(可能需要添加路径信息)并使用ID更新链接标记的href =主题

相关问题