user1728824
user1728824

Reputation: 95

get a json file in local (jquerymobile & phonegap)

I would like to know if it's possible to get a json file which is in local? If yes, how?

I've tried

function test() {
 $.getJSON("c\\file.json", function(json) {
   console.log(json); 
 });
 }

and

    function test() {
      $.getJSON("http://localhost/file.json", function(json) {
       console.log(json); 
      });
    }

I am using wampserver.

Upvotes: 0

Views: 3919

Answers (4)

JRMLSTF
JRMLSTF

Reputation: 85

I have just found a way to load a JSON file stored locally without using the Phonegap File API. It's really easy and worked for me with Cordova 2.7.0 (I have only tested it on an Android device) : I fake a JSONP request using jQuery.ajax(). So your ajax call looks like that :

        $.ajax({
            url: 'data.json',
            crossDomain: true,
            jsonpCallback: 'cb',
            dataType: 'jsonp',
        })
            .fail(function (jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); alert('Failed to load data.'); })
            .done(function (data) {
                app.data = data;
        });

The crossDomain parameter is to force a crossDomain request (JSONP) on the same domain. I also force the callback function name to cb. Also notice that JSONP requests do not support synchronous operation.

Then you have to wrap your JSON data with your callback function like that :

cb(
    {
        "title": "the title,
        "id": 1
    }
);

It's a little tricky and probably not a very good practice. What do you think about it ?

Upvotes: 3

iamjustcoder
iamjustcoder

Reputation: 4852

For the better programming, use the relative path to load the JSON file.

 $.getJSON("file.json", function(json) {
    console.log(json); 
 });

Upvotes: 0

Try with the loopback address, instead of localhost, like this:

$.getJSON("http://127.0.0.1/file.json", function(json) {

Upvotes: 0

Eun
Eun

Reputation: 4178

Try the file format:

file:///C:/folderA/test.html

http://www.cs.tut.fi/~jkorpela/fileurl.html

Upvotes: -1

Related Questions