invitation india
UnexpectedWeb
Connect

Popular Technology Blog where you'll find some interesting things around the web, that you never knew existed.

link Link copied

Serve JSON with Google Apps Script

Share on: link Link copied
Use google script like a Database

You can use Google Apps Script to create a web app that will provide JSON data, based on your parameters. App script obtain the current URL parameters and process parameters and return JSON data.

eg: we create a simple web app, thats provide JSON data (Group) base on class and name

Request URL: https://script.google.com/macros/s/AKfycbxxLxUCpbk02Za-NkzNwNuzO9PHvd-Eo-Iejyj9G4zWtH7ZDk0/exec?name=Ravi&class=5



function doGet(e) {
  var name = e.parameter.name;
  var class = e.parameter.class;
  
  var content = getJSON(name,class); 
  return ContentService.createTextOutput(JSON.stringify(content) ).setMimeType(ContentService.MimeType.JSON); 
  
}


function getJSON(name, class){
  var group;
  if(class <=5){group="A";} 
  else if(class >5 && class <=8){group="B";} 
  else if(class >8 && class <=10){group="C";}
  else if(class >10 && class <=12){group="D";}else{group="none";}
  
  var json = {
    'Name':name,
    'class':class,
    'Group': group 
}; 
  
  return json; 
}

How to use JSON data in simple HTML page with JS



<!DOCTYPE html>
<html>
<body>

<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbxxLxUCpbk02Za-NkzNwNuzO9PHvd-Eo-Iejyj9G4zWtH7ZDk0/exec?name=Ravi&class=8";

xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var myArr = JSON.parse(this.responseText);
    
    document.getElementById("id01").innerHTML = "Group: " + myArr.Group;
  }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

</script>

</body>
</html>



No comments:

Powered by Blogger.