Loading JSON in Phonegap?

时光毁灭记忆、已成空白 提交于 2019-12-21 02:55:12

问题


Basically I have a php script located on a sever that generates a JSON file listing places from a mysql database. Using jQuery Mobile I am developing an application to display these places. My code works in Chrome & Safari, however when I port it over to Phonegap it doesn't work. I have searched all over the internet but can't find an answer :(.

The php file for generating JSON (json.php):

<?php
header('Content-type: application/json');


$server = "localhost";
$username = "xxx";
$password = "xxx";
$database = "xxx";

$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);

$sql = "SELECT * FROM places ORDER BY name ASC";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());

$records = array();

while($row = mysql_fetch_assoc($result)) {
    $records[] = $row;
}

mysql_close($con);

echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>

My Javascript file located within my app (Loads JSON and displays it):

$('#places').bind('pageinit', function(event) {
    getPlaces();
});


function getPlaces() {

    var output = $('#placeList');

    $.ajax({
        url: 'http://www.mysite.com/json.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data, status){
            $.each(data, function(i,item){
                var place = '<li><a href="">'+item.name+'<span class="ui-li-count">'
                + item.checkins+'</span></a></li>';

                output.append(place);
            });
            $('#placeList').listview('refresh');
        },
        error: function(){
            output.text('There was an error loading the data.');
        }
    });

}

The HTML looks like this:

<div data-role="content">
            <h3>Places</h3>
            <ul data-role="listview" id="placeList" data-inset="true">

        </ul>
</div><!-- /content -->

This code works in Chrome & Safari, however when run in the xCode simulator with Phonegap it doesn't load the JSON.

Any help would be much appreciated :)


回答1:


This has probably something to do with the whitelisting, Apple has no faith in any type of uncontrollable data (like iframes or feeds). So they reject every external connection.

Take a look at phonegap.plist in your project rootfolder (xcode) and add your website url to the array 'ExternalHosts'. This will probably work fine after.



来源:https://stackoverflow.com/questions/7882939/loading-json-in-phonegap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!