What I am trying to do is pretty simple: yet something has clearly gone awry.
On the Front-End:
function eval() {
var x = 'Unchanged X'
$.get("/", { entry: document.getElementById('entry').value },
function(data){
x = data;
}
);
$("#result").html(x);
}
On the Back-End:
class MainHandler(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'index.html')
if self.request.get('entry') != '':
#self.response.out.write({'evalresult': self.request.get('entry')})
self.response.out.write(request.get('entry'))
else:
self.response.out.write(template.render(path, {'result': 'Welcome!!'}))
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)
Yet, apparently the function is never being called and #result gets set to ‘Unchanged X’. What am I missing?
NOTE: The callback is NOT being called. I have verified this by placing an alert(“Test”) within the callback function. Any ideas anyone?
First we have the silly mistake:
Semicolons are required after the calls to
over()andout()(roger that? — sorry couldn’t resist)Secondly (the much more subtle problem):
If we ever need intend to translate the
get()into agetJSON()call, (which you might have noted was my original intent from the commented python code that returns a dict), then we need to wrap astr()call aroundself.request.get('entry'). Hence,self.response.out.write({'evalresult': self.request.get('entry')})becomes:
self.response.out.write({'evalresult': str(self.request.get('entry'))})As strings from an HTML field translate to unicode text in Python, at the back-end, we apparently need to convert it to a Python string (as
getJSON()apparently doesn’t like Python’s representation of a unicode string — any ideas why this this is the case anyone?).At any rate, the original problem has been solved. In conclusion: any JSON object with a Python unicode string will not be accepted as a valid JSON object and will fail silently — a nasty gotcha that I can see biting anyone using JQuery with Python on the server-side.