Get a list from the server and print each element surrounded by a span tag

I need to get a list from serveride in python 2.7 to front-end in javascript to print them. Is there any way to do this? I tried passing 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 for looping and printing in the 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); }); 
+4
source share
1 answer

The best way to send and process a list or Python object using JavaScript is to send JSON. You can use json.dumps in your python code

 import json .... my_list = ['one', 'two', 'three', 'four'] self.response.write(json.dumps(my_list) 

Now you get the JSON string. But with jQuery, it will give you a JavaScript object. See jQuery for more details: http://api.jquery.com/jQuery.getJSON/

If you are not using JSON, you can use the string to send the list:

 my_list = ['one', 'two', 'three', 'four'] self.response.write(','.join(my_list)) 
+1
source

All Articles