如何在PHP调用的脚本中创建新变量?附jQuery实时更新代码
Hey, let's tackle this problem step by step. From what I understand, you're using jQuery's load() method to refresh content from sub-PHP scripts every 2 seconds in main.php, and you need to create new variables in those sub-scripts (like smoke.php, pids.php)—either using the status variables you've already fetched in main.php or generating new ones based on fresh data. Here are a few solid solutions to make this work:
Option 1: Pass Variables from main.php to Sub-Scripts via URL Parameters
Since load() sends an HTTP request under the hood, you can pass your existing status variables as URL query parameters to the sub-scripts. This lets the sub-scripts receive the values and create new variables from them.
Update Your jQuery Code in main.php:
$(document).ready(function() { // Inject PHP variables directly into your JavaScript const smokeStatus = <?php echo $smoke_status; ?>; const pidsStatus = <?php echo $pids_status; ?>; const flameStatus = <?php echo $flame_status; ?>; const panicStatus = <?php echo $panic_status; ?>; setInterval(function () { // Pass variables as query parameters in the load URL $('#show').load(`smoke.php?smoke_status=${smokeStatus}`); $('#show2').load(`pids.php?pids_status=${pidsStatus}`); $('#show3').load(`flame.php?flame_status=${flameStatus}`); $('#show4').load(`panic.php?panic_status=${panicStatus}`); }, 2000); });
Use the Variables in smoke.php (Example):
// Safely retrieve the URL parameter (filter it to prevent issues) $smoke_status = intval($_GET['smoke_status']); // Create a new variable based on the status $smoke_display_label = ($smoke_status === 1) ? "⚠️ Smoke Alert Triggered" : "✅ Smoke System Normal"; // Output your content using the new variable echo "<div class='status-card'>{$smoke_display_label}</div>";
Option 2: Fetch Fresh Data & Create Variables Directly in Sub-Scripts
If you want your sub-scripts to be independent (no reliance on main.php's variables), you can connect to the database directly in each sub-script, fetch the latest status, and create new variables from that data.
Example for pids.php:
// Establish your database connection (adjust credentials to match your setup) $db_conn = mysqli_connect('localhost', 'your_db_user', 'your_db_pass', 'your_db_name'); // Fetch the latest PID status from your table $query = "SELECT pids_status FROM device_statuses LIMIT 1"; $result = mysqli_query($db_conn, $query); $row = mysqli_fetch_assoc($result); // Create the base status variable $pids_status = $row['pids_status']; // Create a new variable for styling or additional context $pids_status_class = $pids_status ? "status-error" : "status-success"; // Output styled content echo "<div class='status-indicator {$pids_status_class}'> PID System: " . ($pids_status ? "Malfunctioning" : "Operating Normally") . " </div>"; // Clean up the database connection mysqli_close($db_conn);
Option 3: Share Variables Using PHP Sessions
If you're already using sessions in your app, you can store the status variables in the session from main.php, then access them in your sub-scripts to create new variables.
Store Variables in Session from main.php:
session_start(); // Make sure this is at the top of your script, before any output // After fetching statuses from the database $_SESSION['smoke_status'] = $smoke_status; $_SESSION['pids_status'] = $pids_status; $_SESSION['flame_status'] = $flame_status; $_SESSION['panic_status'] = $panic_status;
Access Session Variables in flame.php (Example):
session_start(); // Start the session to access stored variables // Retrieve the status from session $flame_status = $_SESSION['flame_status']; // Create a new variable for a detailed message $flame_status_message = match($flame_status) { 0 => "No flame detected. All clear.", 1 => "Flame detected in zone 1.", 2 => "Multiple flame zones activated. Evacuate immediately!", default => "Flame sensor status unknown." }; // Output the message echo "<p class='flame-message'>{$flame_status_message}</p>";
Important Notes
- Security First: When using URL parameters, always filter/sanitize values (like using
intval()for numeric statuses) to prevent SQL injection or XSS attacks. - Performance: If you're fetching data directly in sub-scripts every 2 seconds, consider adding caching (like Redis or PHP's
apcu) to reduce database load. - Session Consistency: Ensure every script using sessions calls
session_start()at the very top, before any HTML or output.
内容的提问来源于stack exchange,提问作者RUHAIZAN FAZREEN ASHRAFF MOHD

