Sunday, June 2, 2013

jQuery - get json data from file or service

Json File

{
    "german": {
           "howto": [
            {
                "id": 1,
                "name": "Introduce Yourself",
                "page": "talk_yourself"
            },
            {
                "id": 2,
                "name": "Write Letter",
                "page": "writeletter"
            },
            {
                "id": 3,
                "name": "Asking Questions",
                "page": "ask_question"
            }
        ]
   }
}

Function get json data from file

/****
 * load data from json file (json/howto.json)
 * - how to list (id, name, page)
 */
Utils.loadHowtoJsonFile = function(filename){
    console.log('loadHowtoFile');
   
    $.getJSON(filename, function(data){
        $.each(data.german.howto, function(i,item){
            var howto = "<li class='mobilelistitem1'>" +
            " <a class='howto' id=" + item.page + ">" +
            " <h3>"+item.name+"</h3></a></li>";
           
            $('#howtoList').append(howto);
        });
       
        $('#howtoList').listview("refresh");
       
        //howto item click listener
        $('.howto').click(function(){
            var page = $(this).attr('id');
            $('#j_20').load("view/howto/"+page+".html",function(){
                $('#j_20').trigger("create");
            });
        });
    });
}

Function get json data from web service

/***
 * load json from service
 */
Utils.loadHowto = function(){
    console.log('loadHowto');
    $.ajax({
        type: "GET",
        url: 'http://samcroft.co.uk/demos/updated-load-data-into-phonegap/landmarks.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data, status){
            $.each(data, function(i,item){
                var landmark = "<li class='mobilelistitem1'>" +
                        " <a class='howto' id=" + item.name +
                        " <h3>"+item.latitude+"</h3></a></li>";
                $('#howtoList').append(landmark);
            });
           
            $('#howtoList').listview("refresh");
        },
        error: function(){
            $('#howtoList').text('There was an error loading the data.');
        }
    });
};

0 comments:

Post a Comment