Sunday, March 13, 2016

Simple example of $.ajax to get JSON (JQuery)

  1.  Download the files available in folder speakers
  2. Save them somewhere you can access them over http.
  3. On document ready, toobin.json is loaded and html elements inner html is replaced.
  4. On click of elements in navigation chua.json, sampson.json, sorkin.json or toobin.json is loaded using  $.ajax and elements in index.html are filled with html. Which json to load is being decided by title attribute of of the anchor clicked.

"use strict"; 
$(document).ready(function () {

    //applies to all aside > nav > ul > li > a
    $("aside > nav > ul > li > a").click(function () {
        //fill this array with parts of json file path. please note, with json file location change, you will change it.
        var pathparts = [];

    //anchor with title toobin
}); // end ready

function consumeJSON(jsonFileURL) {
        url: jsonFileURL,
        //default method is GET so need not mention
        dataType: "text", // you may pass json here and avoid parseJSON below
        success: function (data) {

            //data downloaded so we call parseJSON function 
            //and pass downloaded data
            var json = $.parseJSON(data);
            //use html() instead of text() below, note that input has html tags too. see the json also to observe these tags.
            //each json has single element under speakers collection
            // important : we could also prepare whole html and set html inside main element
            $("main > h2").html(json.speakers[0].month + "<br/>" + json.speakers[0].speaker);
            $("main > h1").html(json.speakers[0].title);
            $("main > img").attr("src", json.speakers[0].image);
            $("main > p").html(json.speakers[0].text);

No comments:

Post a Comment