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

已有Cordova项目,如何开发PhoneGap应用并连接远程数据库读取数据

Hey there! Since you already have a Cordova project up and running, let’s break down how to connect it to a remote database, fetch classroom location data, and display the building/floor info using AJAX, JSON, PHP, and jQuery Mobile. I’ll keep this practical and code-focused—let’s dive in:

1. Set Up the PHP Backend (Web Server)

First, you’ll need a PHP script on your web server to handle database queries and return data as JSON. This acts as a secure middleman (never connect directly to the database from your app—bad security practice!).

Example PHP Script (get_classrooms.php)

<?php
// Database credentials (replace with your own)
$host = "your_db_host";
$dbname = "your_db_name";
$username = "your_db_user";
$password = "your_db_password";

try {
    // Connect to database using PDO (more secure than mysqli)
    $conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Query to fetch classroom locations (adjust table/column names to match your DB)
    $stmt = $conn->prepare("SELECT classroom_name, building, floor FROM classrooms");
    $stmt->execute();

    // Fetch all results as an associative array
    $classrooms = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Return data as JSON
    header("Content-Type: application/json");
    echo json_encode($classrooms);

} catch(PDOException $e) {
    // Handle errors (return error message as JSON)
    header("Content-Type: application/json");
    echo json_encode(array("error" => $e->getMessage()));
}

$conn = null;
?>

Test this script by visiting https://your-server-url/get_classrooms.php in a browser—you should see a JSON array of your classroom data.

2. Configure Your Cordova Project

Before making AJAX calls, you need to allow your app to connect to your web server. Use the cordova-plugin-whitelist (it’s included by default in newer Cordova versions, but double-check):

Update config.xml

Add these lines to allow requests to your server (replace https://your-server-url.com with your actual server domain):

<allow-navigation href="https://your-server-url.com/*" />
<access origin="https://your-server-url.com" />

For testing, you can use <access origin="*" /> (but don’t leave this in production—it’s insecure!).

3. Build the jQuery Mobile UI

In your Cordova project’s www folder, set up a basic jQuery Mobile page to display the classroom data. First, include jQuery and jQuery Mobile in your index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Classroom Finder</title>
    <!-- jQuery Mobile CSS -->
    <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    <!-- jQuery Mobile JS -->
    <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
    <div data-role="page" id="classroomPage">
        <div data-role="header">
            <h1>Classroom Locations</h1>
        </div>
        <div data-role="content" id="classroomList">
            <!-- Classroom data will load here -->
            <p>Loading locations...</p>
        </div>
    </div>
    <script src="js/app.js"></script>
</body>
</html>
4. Use AJAX to Fetch & Display Data

Create www/js/app.js to handle the AJAX request and render the data:

$(document).on("pagecreate", "#classroomPage", function() {
    // Fetch data from PHP script
    $.ajax({
        url: "https://your-server-url.com/get_classrooms.php",
        type: "GET",
        dataType: "json",
        success: function(data) {
            // Clear loading message
            $("#classroomList").empty();

            // Check for errors from PHP
            if (data.error) {
                $("#classroomList").append("<p>Error loading data: " + data.error + "</p>");
                return;
            }

            // Loop through classrooms and create list items
            $.each(data, function(index, classroom) {
                var listItem = $("<li>").append(
                    $("<a>").html(
                        "<h3>" + classroom.classroom_name + "</h3>" +
                        "<p><strong>Building:</strong> " + classroom.building + "</p>" +
                        "<p><strong>Floor:</strong> " + classroom.floor + "</p>"
                    )
                );
                $("#classroomList").append(listItem);
            });

            // Refresh jQuery Mobile listview to apply styles
            $("#classroomList").listview().listview("refresh");
        },
        error: function(xhr, status, error) {
            $("#classroomList").html("<p>Failed to load data: " + error + "</p>");
        }
    });
});
5. Key Notes for Success
  • CORS Issues: If you run into cross-origin errors, add these CORS headers at the top of get_classrooms.php (adjust for production):
    header("Access-Control-Allow-Origin: *"); // Allow all origins (restrict to your app's domain in production)
    header("Access-Control-Allow-Methods: GET");
    
  • Security: In production, never hardcode database credentials in your PHP script—use environment variables. Even though you’re only reading data, sanitize any future user input if you add search/filter features.
  • Testing: Test on a real device or emulator—some browsers block local AJAX requests, but Cordova handles this properly once configured.

That’s it! Your Cordova/PhoneGap app will now fetch classroom data from your remote database and display it neatly using jQuery Mobile.

内容的提问来源于stack exchange,提问作者Tiago Silvérrio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:19:05