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

使用Cordova转网页为App时无法获取MySQL数据的求助

问题:Cordova应用无法通过PHP API获取MySQL数据

我掌握JS和PHP知识,想用Cordova开发Android与iOS应用,但在开发数据库驱动应用时,无法从MySQL获取数据。我知道Cordova不能直接解析PHP脚本与MySQL通信,所以搭建了返回JSON格式数据的API部署在服务器,但Cordova里的JS请求无返回结果,HTML页面显示空单元格,浏览器开发者工具也看不到API请求记录。

API代码(PHP):

<?php
header('Content-Type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "yourdbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tbl_students";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    echo json_encode($data);
} else {
    echo "0 results";
}
$conn->close();
?>

主JS文件代码:

document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
    fetchData();
}
function fetchData() {
    var url = 'http://localhost/yourproject/api.php';
    cordova.plugin.http.sendRequest(url, {
        method: 'GET',
        headers: {},
        timeout: 5000
    }, function (response) {
        displayData(JSON.parse(response.data));
    }, function (error) {
        console.error(error);
    });
}
function displayData(data) {
    var tableBody = document.querySelector('#studentTable tbody');
    data.forEach(function (student) {
        var row = tableBody.insertRow();
        var idCell = row.insertCell(0);
        var nameCell = row.insertCell(1);
        var ageCell = row.insertCell(2);
        idCell.innerHTML = student.id;
        nameCell.innerHTML = student.name;
        ageCell.innerHTML = student.age;
    });
}

解决方案

1. 修正API的访问URL

  • http://localhost/yourproject/api.php仅能在本地浏览器访问,Cordova真机/模拟器无法识别这个地址,需替换为服务器的公网IP/域名(局域网测试用本地IP,比如http://192.168.1.100/yourproject/api.php)。
  • 先在浏览器直接访问修改后的URL,确认能返回标准JSON数据(如[{"id":1,"name":"张三","age":20}]),若返回"0 results"需检查数据库是否有数据或SQL语句是否正确。

2. 配置Cordova的安全策略

  • 确保安装了cordova-plugin-whitelist插件:
    cordova plugin add cordova-plugin-whitelist
    
  • 在项目根目录的config.xml中添加允许访问服务器的规则:
    <access origin="http://你的服务器IP或域名/*" />
    <allow-navigation href="http://你的服务器IP或域名/*" />
    

3. 统一API的JSON返回格式

  • 当前API无数据时返回字符串"0 results",前端JSON.parse()会报错,需修改为返回空数组:
    } else {
        echo json_encode([]); // 返回空数组而非字符串
    }
    
  • 提前初始化$data变量,避免无数据时json_encode($data)报错,在$result = $conn->query($sql);前添加:
    $data = [];
    

4. 调试请求错误细节

  • 完善错误回调的输出,方便定位问题:
    function (error) {
        console.log('请求错误详情:', error.status, error.error, error.response);
        alert('请求失败: ' + error.error);
    }
    
  • 使用Chrome调试工具(chrome://inspect连接安卓设备)查看控制台的错误信息,确认是网络问题、权限问题还是数据格式问题。

5. 验证数据库连接与SQL正确性

  • 检查PHP代码中的数据库连接参数($servername、$username等)是否正确,确认MySQL服务正常运行。
  • 直接在数据库客户端执行SELECT * FROM tbl_students,确认有数据返回,且字段名(id、name、age)与前端代码中的字段一致。

内容的提问来源于stack exchange,提问作者Alexis Nimubona

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:11:21