Skip to content Skip to sidebar Skip to footer

Pass JSON To JQuery Function Javascript

We have a very simpel Google Apps Script Web App, which purpose is to show JSON data in a HTML drop-down-list. The JSON file exists in Google Drive. Inspiration code from: http://j

Solution 1:

You have to return the data in getJson() function, and when calling it, you need to pass a callback, with withSuccessHandler(), as such:

in HTML:

function justLog(e){
   console.log(e);
}

$('#fetch').click(function(s) {
   google.script.run.withSuccessHandler(justLog).getJson(); // Runs the function "getJson();" in Code.gs
});

in code.gs, finish the function with:

return JSONDATA;

Solution 2:

Thanks Kriggs! This worked out great:

Index.html:

<!DOCTYPE html>
<html>
  <head>

  <select id="dropDownDest">
</select>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>

<script>

function onSuccess(json) {

       $.each(json.Cars, function (key, value) {
            $("#dropDownDest").append($('<option></option>').val(value.carID).html(value.CarType));
        });

        $('#dropDownDest').change(function () {
            alert($(this).val());
            //Code to select image based on selected car id
        });

      }

      google.script.run.withSuccessHandler(onSuccess)
          .jsonData();

    </script>

  </head>
</html>

Code.gs:

function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

    function jsonData() {

     var a = {
                Cars: [{
                    "CarType": "BMW",
                    "carID": "bmw123"
                }, {
                    "CarType": "mercedes",
                    "carID": "merc123"
                }, {
                    "CarType": "volvo",
                    "carID": "vol123r"
                }, {
                    "CarType": "ford",
                    "carID": "ford123"
                }]
            }; 

      Logger.log(a);
      return a;

    }

Post a Comment for "Pass JSON To JQuery Function Javascript"