You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向含HTML、JavaScript、PHP的PHP文件发请求及更新首页PHP文件

Hey there, let's work through getting these three files communicating properly— I’ve tackled similar setup snags before, so let’s break this down step by step.

1. First: Fix the Index Code File ↔ index.php Connection

Your index code file (let’s call it table-utils.php for clarity) holds the functions to fetch table data, so you need to make sure index.php can access those functions correctly:

  • Include the file properly at the top of index.php using a reliable path. If it’s in the same directory:
    // index.php - top of the file
    require_once 'table-utils.php'; // Use require_once to avoid duplicate includes
    
  • Test the function call to confirm you’re getting valid data. Add a quick debug check:
    $tableData = getTableData(); // Replace with your actual function name
    var_dump($tableData); // Check if this outputs the expected table structure
    

Pro tip: If you get a "function not defined" error, double-check the file path—relative paths can break if index.php is in a subfolder!

2. Get the updatable File Talking to Mobile & Your Index Code

The updatetable file acts as your API endpoint for mobile requests. Let’s make sure it can receive data, use your index functions, and send back a clear response:

// updatable.php
// Handle cross-origin requests if mobile is on a different domain (adjust for production!)
header("Access-Control-Allow-Origin: *"); 
header("Content-Type: application/json");

// Receive mobile request data (assuming it's sent as JSON)
$requestPayload = json_decode(file_get_contents('php://input'), true);

// Validate required data first—don't skip this!
if (!isset($requestPayload['row_id']) || !isset($requestPayload['new_value'])) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

// Connect to your index code file to use update functions
require_once 'table-utils.php';
$updateSuccess = updateTableRow($requestPayload['row_id'], $requestPayload['new_value']); // Your update function

// Send a clear response back to mobile
echo json_encode([
    'status' => $updateSuccess ? 'success' : 'error',
    'message' => $updateSuccess ? 'Table updated' : 'Update failed'
]);

Test this endpoint with a tool like Postman: send a POST request with JSON body to confirm it returns the right status.

Once the backend is sorted, you need index.php’s JS to pull the latest table data (after mobile updates). Here’s a simple way using the Fetch API:

// Inside index.php's <script> tag
function refreshTable() {
    // Fetch updated data from your index code (or a dedicated endpoint)
    fetch('table-utils.php?action=get_latest') // Add a query param to trigger data fetch
        .then(response => response.json())
        .then(data => {
            // Update the table DOM with fresh data
            const tableBody = document.querySelector('#your-table-body-id');
            tableBody.innerHTML = ''; // Clear old rows
            
            data.forEach(row => {
                const newRow = document.createElement('tr');
                newRow.innerHTML = `<td>${row.id}</td><td>${row.content}</td>`; // Match your table structure
                tableBody.appendChild(newRow);
            });
        })
        .catch(err => console.error('Failed to refresh table:', err));
}

// Optional: Auto-refresh every 5 seconds to catch mobile updates
setInterval(refreshTable, 5000);

// Or, if you want real-time updates without polling, look into WebSockets!
Quick Troubleshooting Checks
  • Check PHP error logs: Most issues (like missing functions, database errors) show up here—enable error logging in your php.ini if you haven’t.
  • Inspect browser dev tools: Use the Network tab to see if your JS fetch requests are returning 200 OK or errors.
  • Verify file permissions: Make sure all three files have read/write permissions that your server can access.

内容的提问来源于stack exchange,提问作者Nic Parmee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:38:20