求助:如何在Cordova应用中用MySQL、jQuery实现Materialize标签页数据展示?
Hey there! Let's walk through how to get your Cordova app pulling data from MySQL and displaying it in Materialize tabs—whether you prefer using jQuery or vanilla JavaScript with PHP. Since you can't connect directly to MySQL from a frontend app (big security no-no!), we'll use a simple PHP backend as the middleman. Here's a complete, working solution tailored for the latest Materialize and jQuery versions:
First, create a PHP file (e.g., get-data.php) on your server to handle database queries and return data as JSON. This acts as the bridge between your Cordova app and MySQL:
<?php // Enable CORS to allow Cordova app access (adjust origin if needed for production) header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); // Database credentials (replace with your own) $host = "your_database_host"; $db_name = "your_database_name"; $username = "your_db_username"; $password = "your_db_password"; try { // Connect to database using PDO (more secure than mysqli) $conn = new PDO("mysql:host=$host;dbname=$db_name", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Fetch data for each tab (adjust queries to match your table structure) $stmt = $conn->prepare("SELECT * FROM tab1_data"); $stmt->execute(); $tab1Data = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt = $conn->prepare("SELECT * FROM tab2_data"); $stmt->execute(); $tab2Data = $stmt->fetchAll(PDO::FETCH_ASSOC); // Return combined data as JSON echo json_encode([ "tab1" => $tab1Data, "tab2" => $tab2Data ]); } catch(PDOException $e) { // Return error message if something goes wrong echo json_encode(["error" => $e->getMessage()]); } $conn = null; ?>
Test this endpoint by visiting it in your browser—you should see a JSON object with your tab data (or an error message if something's misconfigured).
Set up your Cordova app's HTML with Materialize's tab component, leaving empty containers to inject dynamic data:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Materialize CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <title>Tab Data from MySQL</title> </head> <body> <div class="container"> <div class="row"> <!-- Materialize Tabs Navigation --> <div class="col s12"> <ul class="tabs"> <li class="tab col s3"><a href="#tab1">Tab 1</a></li> <li class="tab col s3"><a href="#tab2">Tab 2</a></li> </ul> </div> <!-- Tab Content Containers --> <div id="tab1" class="col s12"> <div id="tab1-content" class="collection"></div> </div> <div id="tab2" class="col s12"> <div id="tab2-content" class="collection"></div> </div> </div> </div> <!-- jQuery (for Option 1) --> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <!-- Materialize JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <!-- Your Custom Script --> <script src="js/app.js"></script> </body> </html>
In your app.js file, initialize Materialize tabs and use jQuery's ajax method to pull data from the PHP endpoint, then render it into the tabs:
$(document).ready(function() { // Initialize Materialize Tabs $('.tabs').tabs(); // Fetch data from PHP backend $.ajax({ url: 'https://your-server-url/get-data.php', // Replace with your PHP endpoint URL type: 'GET', dataType: 'json', success: function(data) { // Render Tab 1 Data if (data.tab1.length > 0) { data.tab1.forEach(item => { // Adjust the HTML to match your data fields (e.g., item.title, item.description) $('#tab1-content').append(` <a href="#!" class="collection-item">${item.title} - ${item.description}</a> `); }); } else { $('#tab1-content').append('<p class="center-align">No data found for Tab 1</p>'); } // Render Tab 2 Data if (data.tab2.length > 0) { data.tab2.forEach(item => { $('#tab2-content').append(` <a href="#!" class="collection-item">${item.name} - ${item.value}</a> `); }); } else { $('#tab2-content').append('<p class="center-align">No data found for Tab 2</p>'); } }, error: function(xhr, status, error) { console.error('Error loading data:', error); $('#tab1-content').append('<p class="center-align red-text">Failed to load Tab 1 data</p>'); $('#tab2-content').append('<p class="center-align red-text">Failed to load Tab 2 data</p>'); } }); });
If you want to skip jQuery, use the native Fetch API instead. Update your app.js to this:
document.addEventListener('DOMContentLoaded', function() { // Initialize Materialize Tabs const tabs = document.querySelectorAll('.tabs'); M.Tabs.init(tabs); // Fetch data using native Fetch API fetch('https://your-server-url/get-data.php') .then(response => response.json()) .then(data => { const tab1Container = document.getElementById('tab1-content'); const tab2Container = document.getElementById('tab2-content'); // Render Tab 1 Data if (data.tab1.length > 0) { data.tab1.forEach(item => { const listItem = document.createElement('a'); listItem.className = 'collection-item'; listItem.href = '#!'; listItem.textContent = `${item.title} - ${item.description}`; tab1Container.appendChild(listItem); }); } else { tab1Container.innerHTML = '<p class="center-align">No data found for Tab 1</p>'; } // Render Tab 2 Data if (data.tab2.length > 0) { data.tab2.forEach(item => { const listItem = document.createElement('a'); listItem.className = 'collection-item'; listItem.href = '#!'; listItem.textContent = `${item.name} - ${item.value}`; tab2Container.appendChild(listItem); }); } else { tab2Container.innerHTML = '<p class="center-align">No data found for Tab 2</p>'; } }) .catch(error => { console.error('Error loading data:', error); const tab1Container = document.getElementById('tab1-content'); const tab2Container = document.getElementById('tab2-content'); tab1Container.innerHTML = '<p class="center-align red-text">Failed to load Tab 1 data</p>'; tab2Container.innerHTML = '<p class="center-align red-text">Failed to load Tab 2 data</p>'; }); });
Whitelist Your Server: In your Cordova
config.xml, add these lines to allow your app to access the PHP endpoint:<access origin="https://your-server-url/*" /> <allow-navigation href="https://your-server-url/*" />For local testing with
localhost, use<access origin="http://localhost/*" />.Network Permissions: Ensure your Android app has internet access by adding this to
config.xml:<uses-permission android:name="android.permission.INTERNET" />Debugging: Use Chrome DevTools (
chrome://inspect) to debug your Cordova app—check the Console tab for AJAX/Fetch errors, and verify your PHP endpoint returns valid JSON.
内容的提问来源于stack exchange,提问作者Milind Chaudhari

