[英]How to pass and get URL parameters in jQuery using php $_GET?
我做了一个暗模式功能,可以更改应用程序的背景颜色和文本颜色。 它工作正常,但问题是当我转到value="dark"
上的其他页面时,值属性被重置,新页面位于value="light"
。 我必须将暗模式值发送到其他页面。
我搜索了我的问题,发现我不能使用$ajax
(因为url
是固定的)。 我知道如何使URL
参数(例如url/foo?bar=value
和$_GET['bar']
等于值,但是我不知道将此类代码放在哪里。
// This is in the <head> of base.blae.php
<button id="dm" style="margin: 19px;" class="btn btn-dark" name="mode" value="light" onclick="
Darkmode(this);
">Darkmode</button>
// JS file
function Darkmode(self){
if($('#dm').val() === 'light'){
Color.backgroundColor('DarkSlateGray');
Color.textColor('white');
$('#dm').val('dark');
} else {
Color.backgroundColor('white');
Color.textColor('black');
$('#dm').val('light');
}
}
我想使用php
URL
参数。 例如,使url
像这样http://localhost:8000/events?mode=dark
并获取值$_get['mode']
。 我知道JS
是客户端,而PHP
是服务器端。 但是我认为有一种方法可以使这项工作生效。 您可以用代码解释它,我应该放在哪里? 感谢大伙们!
使用本地存储/会话存储来保存/获取状态
function Darkmode(self){
if($('#dm').val() === 'light') {
Color.backgroundColor('DarkSlateGray');
Color.textColor('white');
$('#dm').val('dark');
localStorage.setItem('mode', 'dark');//set the state if the user pushes the button
} else {
Color.backgroundColor('white');
Color.textColor('black');
$('#dm').val('light');
localStorage.setItem('mode', 'light');
}
}
var mode = localStorage.getItem('mode');//get the state from storage when you navigate to a new page
if(mode === 'dark') { // if the mode is black we change the colors, if no state is stored (or is white) we keep it white
Color.backgroundColor('white');
Color.textColor('black');
$('#dm').val('light');
localStorage.setItem('mode', 'light');
} else {
Color.backgroundColor('DarkSlateGray');
Color.textColor('white');
$('#dm').val('dark');
localStorage.setItem('mode', 'dark');
}
如果要使用get参数,则需要执行以下操作
var mode = '<?php echo isset($_GET['mode'])?$_GET['mode']:"light";?>';//create a js variable using php ternary operator
if(mode === 'light') {
Color.backgroundColor('DarkSlateGray');
Color.textColor('white');
$('#dm').val('dark');
} else {
Color.backgroundColor('white');
Color.textColor('black');
$('#dm').val('light');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.