[英]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.