I need to get a list from the serverside in python 2.7 to the front-end in javascript to print them. Is there a way to do this? I tried to pass the list through “self.response.out.write(my_list)”.
import webapp2
import jinja2
import os
import logging
from google.appengine.ext import db
import random
from google.appengine.api import users
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + '/template'))
class MainPage(webapp2.RequestHandler):
def get(self):
# Print webpage
template_values = {}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
def post(self):
my_list = ['one', 'two', 'three', 'four']
self.response.out.write(my_list)
app = webapp2.WSGIApplication([('/', MainPage),],debug=True)
Javascript code to loop through list and print them in console.
function refresh(e) {
console.log('Refresh.');
addNewWord();
}
function addNewWord() {
console.log('Add new words');
$.ajax('/',{
type: 'POST',
data: {
},
success: handleResponse
});
}
function handleResponse(data) {
console.log('Got from server:' + data);
for (var i = 0; i <data.length; i++) {
console.log(data[i]);
}
}
$(document).ready(function() {
$('#refreshButton').click(refresh);
});
The best way to send and proces a list or Python object with JavaScript is to send JSON.
You can use
json.dumpsin your python codeNow you receive a JSON string. But using jQuery it will give you a JavaScript object. See jQuery for the details: http://api.jquery.com/jQuery.getJSON/
If you don not use JSON, you can use a string to send the list :