A simple Python and Ajax example. How to send a response using Python?

I am testing code with Python and Javascript trying to set up an Ajax system. Basically, I just want to enter a word and return the Python code. Here is my html / javascript:

<html> <head> <title>Simple Ajax Example</title> <script language="Javascript"> function xmlhttpPost(strURL) { var xmlHttpReq = false; var self = this; // Mozilla/Safari/Chrome if (window.XMLHttpRequest) { self.xmlHttpReq = new XMLHttpRequest(); } // IE else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } self.xmlHttpReq.open('POST', strURL, true); self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); self.xmlHttpReq.onreadystatechange = function() { if (self.xmlHttpReq.readyState == 4) { updatepage(self.xmlHttpReq.responseText); } } self.xmlHttpReq.send(getquerystring()); } function getquerystring() { var form = document.forms['f1']; var word = form.word.value; qstr = 'w=' + escape(word); // NOTE: no '?' before querystring return qstr; } function updatepage(str){ document.getElementById("result").innerHTML = str; } </script> </head> <body> <form name="f1"> <p>word: <input name="word" type="text"> <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/ajaxtest")'></p> <div id="result"></div> </form> </body> </html> 

and here is my python:

 class AjaxTest(BlogHandler): def get(self): user = self.get_user() self.render('ajaxtest.html', user = user) def post(self): user = self.get_user() word = self.request.get('w') logging.info(word) return '<p>The secret word is' + word + '<p>' #having print instead of return didn't do anything 

When I register a word, it displays correctly and when I hardcode str:

 function updatepage(str){ document.getElementById("result").innerHTML = str; } 

It displays this correctly, but right now without hardcoding it is not showing anything. How should I send a response? I use webapp2 as my Python infrastructure and Jinja2 as a template engine, although I don't think this is related to this. Do I need to send HTTP headers?

+4
source share
1 answer

If your problem makes it difficult to return a string from the post method, without rendering the template, you can use the write method to accomplish this:

self.response.write('')

I believe you can change the headers just by changing self.response.headers

+4
source

Source: https://habr.com/ru/post/1493281/


All Articles