![](/img/trans.png)
[英]Run PHP script in background on submit button click without page reload
[英]Run PHP script on link click without page refresh
好的,所以我在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?
您可以在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");
由于您已经在<link />
标记中使用了id="theme"
,因此我们可以使用AJAX轻松地在jQuery中设置内容。
所以,你这样给出一个主题请求:
$.getScript("theme.php?teema=theme");
在PHP中:
header("Content-type: text/javascript");
$('#theme').attr('href', 'css/<?php echo $_GET['teema']; ?>');
更改此链接的内容( $('$#theme').attr('href', 'css/' + selectedtheme +'.css');
您也可以在javascript中设置cookie( document.cookie = 'theme=' + selectedtheme
)
您可以简单地发出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')
})
});
这将解析链接href
的teema
值,调用该href
(可能需要添加路径信息)并更新ID = theme的链接标记的href
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.