Bottle AJAX Presentation Form (Python)

I'm having some problems with using an AJAX connection using the Bottle environment. This is my first time using AJAX, so most likely I'm just wrong. Hope the Bottle / AJAX guru can point this newbie in the right direction. Here is the code I'm using:

#!/usr/bin/env python from bottle import route, request, run, get # Form constructor route @route('/form') def construct_form(): return ''' <html> <head> <script type="text/javascript"> function loadXMLDoc() { xmlhttp = new XMLHTTPRequest(); xmlhttp.onReadyStateChange = function() { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("responseDiv").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "/ajax", true); xmlhttp.send(); } </script> </head> <body> <form> <input name="username" type="text"/> <input type="button" value="Submit" onclick="loadXMLDoc()"/> </form> <div id="responseDiv">Change this text to what you type in the box above.</div> </body> </html> ''' # Server response generator @route('/ajax', method='GET') def ajaxtest(): inputname = request.forms.username if inputname: return 'You typed %s.' % (inputname) return "You didn't type anything." run(host = 'localhost', port = '8080') 
+6
source share
1 answer

There are several issues here.

  • Javascript is case sensitive. XMLHTTPRequest must be XMLHttpRequest. You should have seen an error about this in your Javascript console.
  • onReadyStateChange must be onreadystatechange.
  • If you fix these two problems, your AJAX call will work, but you will only ever get "You did not enter anything." answer. This is because you are using GET. You need to change your code so that the form values ​​are published using the POST method.

Also, why aren't you using jQuery to create AJAX? That would make your life a lot easier. :)

+4
source

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


All Articles