我在 URL 中傳遞 PHP 變量,所以我的頁面鏈接看起來像這樣www.example.com?redirect=neworders
基於$_GET['redirect']
值,我在示例中創建了頁面的內容input
然后在<script>
部分,我想根據PHP
值調用帶有參數的函數。
我當前的代碼現在正在工作但我相信這不是正確的方法,盡管我檢查了多個線程並且通常答案是我提到的選項之一。
如果我做對了有什么建議嗎? 我在代碼中添加了注釋以了解我的情況。 非常感謝。
<?php
//my url can be either www.example.com?redirect=neworders or www.example.com?redirect=deliveredorders
switch($_GET['redirect']) {
case 'neworders':
$page = 'Backlog';
break;
case 'deliveredorders':
$page = 'Shipment';
break;
}
?>
<body>
//based on $page value, I create the input value with a specific id
<?php
if ( $page == 'neworders') {
echo '<input type="text" id="BacklogName" placeholder="enter order number">'; }
elseif ( $page == 'deliveredorders') {
echo '<input type="text id="ShipmentName" placeholder="enter order number then serial number">';
}
?>
<button type="button" id="submitButton">Submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
<script>
$(document).ready(function() {
//I have some functions declared here to use based on $page value
function submitEvent(element, input) {
element.click(function() {
alert(input.val());
});
}
//based on $page value, intialize the function with exact selectors
//first Option came to my mind : check the $page value and echo function intialization as string
<?php
if ( $page == 'neworders') {
echo 'submitEvent($("#submitButton"), $("#BacklogName"));'; }
elseif ( $page == 'deliveredorders') {
echo 'submitEvent($("#submitButton"), $("#ShipmentName"));'; }
?>
//second option came to my mind : use javascript 'if else' and only echo the $page value
if ("<?php echo $page; ?>" == "neworders") {
submitEvent($("#submitButton"), $("#BacklogName")); }
else if ("<?php echo $page; ?>" == "deliveredorders") {
submitEvent($("#submitButton"), $("#ShipmentName"));
}
});
</script>