首页 > 解决方案 > 无法通过 AJAX (Cordova) 调用 PHP 文件

问题描述

我是初学者。我一直在尝试使用cordova/phonegap 开发一个应用程序。我制作了一个示例数据库并将其上传到免费主机上,并对 php 文件进行了同样的操作。我可以在网络/桌面上从数据库中检索数据,但它在模拟器上不起作用。我应该怎么办?

我试图发现发生了什么:到目前为止我所知道的是javascript文件是好的,因为它的“警报”功能正在工作。我知道我的 php 文件不能在 phonegap 上工作,因为我试图更新我的数据库但它没有工作。

getDados.php(在网络主机上):

<?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
    //Conectando ao banco de dados
    $con = new mysqli("sql10.freemysqlhosting.net", "login_bd", "senha_bd", "nome_bd");
    if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());

    //Consultando banco de dados
    $qryLista = mysqli_query($con, "SELECT * FROM usuarios");    
    while($resultado = mysqli_fetch_assoc($qryLista)){
        $vetor[] = array_map('utf8_encode', $resultado); 
    }    

    //Passando vetor em forma de json
    echo json_encode($vetor);
?>

index.html(在我的本地机器上):

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="utf-8">
        <title>AJAX, JSON E PHP</title>
        <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
        <script src="http://IP DA MÁQUINA LOCAL/geek_phonegap/www/ajax.js"></script>
    </head>
    <body>
        <table border="1" width="500">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Usuario</th>
                    <th>Senha</th>
                </tr>
            </thead>
            <tbody id="tabela"></tbody>
        </table>
        <button onclick="funcao1()">Alert</button>
    </body>
    <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
</html>

ajax.js(本地机器):

function funcao1()
{
    alert("Está chamando o arquivo ajax.js!");
}

$(document).ready(function(){
    $('#tabela').empty(); //Limpando a tabela
    $.ajax({
        type:'post',        //Definimos o método HTTP usado
        dataType: 'json',   //Definimos o tipo de retorno
        url: 'http://uniapp.orgfree.com/getDados.php',//Definindo o arquivo onde serão buscados os dados
        success: function(dados){
            for(var i=0;dados.length>i;i++){
                //Adicionando registros retornados na tabela
                $('#tabela').append('<tr><td>'+dados[i].id+'</td><td>'+dados[i].usuario+'</td><td>'+dados[i].senha+'</td></tr>');
            }
        }
    });
});

标签: javascriptphpajaxcordovaphonegap

解决方案


推荐阅读