Monday, March 28, 2011

HW9 Grades and Solution

The grades are in your inbox. Below is my sample partial solution. I think a few of you were trying to make this a lot more complicated that it is. All we are doing is turning an object into a string and back, and thats done by the library.

The solution you see below is running here. Of course, you would put all your html, python, and javascript in separate files. I'm putting them in one to make it easier to understand.

"""A sample partial solution to the json homework"""        
class JasonTest(webapp.RequestHandler):
    def get(self): #/jtest will draw a chart, /jtest?fmt=json will return the json that is the data for the chart
        if self.request.get('fmt') == 'json':
            jsonObject = {'qtext': "How easy is this?", 'choices': ["Super easy", "Very easy", "Impossible"], 'votes': [5,10,20]}
            self.response.out.write(json.dumps(jsonObject))
            self.response.headers.add_header('Content-type', 'text/json')
        else:
            self.response.out.write("""
<html>
  <head>
    <title>Hello</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>    
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
    
      // Load the Visualization API and the piechart package.
      google.load('visualization', '1', {'packages':['corechart']});
      
      //callback that generates an XHR call, when that returns we create the graph.
      function drawChart() {
        $.ajax('/jtest',{
          type: 'GET',
          data: {fmt: 'json'},
          dataType: 'json',
          success: function(question){ //got the json data, now make the graph
            // Create our data table.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Choice');
            data.addColumn('number', 'Votes');
            rows = []
            for (var i=0; i < question.choices.length; i++){
               rows[i] = [question.choices[i], question.votes[i]];
            }
            data.addRows(rows);
            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
            chart.draw(data, {width: 400, height: 240, is3D: true, title: question.qtext});            
          }
          });
     }

    $(document).ready(function(){ 
      // Set a callback to run when the Google Visualization API is loaded.
      google.setOnLoadCallback(drawChart);
    });
    </script>

  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>
            """)
        
        

No comments:

Post a Comment