如何使用phonegap中的json从php获取数据

时间:2014-12-30 13:56:53

标签: php android jquery json cordova

如何使用phonegap中的json从 php获取数据, 在服务器xampp上,我只写了以下代码 replay.php 。我从this line获取了这些示例,并且我想提及this question from stackover flow,尝试根据它进行制作,但我的android模拟器没有响亮,请帮助我这个主题,我是新的 phonegap和android,

replay.php

<?php
header('Content-Type: application/json');
$choice =$_POST["button"];
$cars = array("Honde", "BMW" , "Ferrari");
$bikes = array("Ducaite", "Royal Enfield", "Harley Davidson");
if($choice == "cars") print json_encode($cars);
    else 
print json_encode($bikes);
?>

在eclipse中,我在 index.html

中编写以下代码
<!DOCTYPE html>
<html>
<head>
    <script charset="utf&minus;8" type="text/javascript">
    function connect(e)
    {
        var term= {button:e};
        $.ajax({
        url:'http://localhost/Experiements/webservices/reply.php',
        type:'POST',
        data:term,
        dataType:'json',
        error:function(jqXHR,text_status,strError){
        alert("no connection");},
        timeout:60000,
        success:function(data){
            $("#result").html("");
                for(var i in data){
                    $("#result").append("<li>"+data[i]+"</li>");
                }
            }
        });
    }
    </script>
</head>
<body>
    <center><b>Bikes or Cars</b></center>
    <center><input onclick="connect(this.value)" type="button" value="cars" /></center>
    <center><input onclick="connect(this.value)" type="button" value="bikes" /></center>
    <center><b>Results</b></center>
    <ul id="result"></ul>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

如果我错了,请纠正我,但你只是要求 HOW 来执行此过程,对吗?您的问题听起来像是来自&#34;教程&#34;而不是你的申请?以下是我使用PhoneGap在我自己的私人应用程序中执行此功能的方法。

我的AJAX调用看起来像这样,减去自定义数据操作:

$.ajax({
    url: "http://www.mywebsite.com/myscript.php",    // path to remote script
    dataType: "JSON",                                // data set to retrieve JSON
    success: function (data) {                       // on success, do something...
        // grabbing my JSON data and saving it
        // to localStorage for future use.
        localStorage.setItem('myData', JSON.stringify(data));
    }
});

我的PHP脚本功能如下:

// PHP headers (at the top)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

// connect to your database and perform your query    

// then build your output...
while($row = mysqli_fetch_array($result)) {
    $output[] = array (
        "id" => $row['id'],
        "firstname" => $row['firstname'],
        "lastname" => $row['lastname']
    );
}

echo json_encode($output);

上面的过程将为您提供PHP脚本(您的数据库)中保存的localStorage文件。然后,您可以使用localStorage输出数据,而无需持续执行AJAX请求。

例如:

var myData = JSON.parse(localStorage.getItem('myData'));
var i;

for (i = 0; i < myData.length; i = i + 1) {
   console.log(myData[i].firstname);      // this should output the firstnames.
}