Want to send a JSON AJAX request to a CherryPy back-end using jQuery? Here's a quick example.
Let's create a sample request that will send JSON data to the back-end, to see if a username exists in the system:
$(document).ready(function() {
//put together a sample request, to find out if a username is taken
var requestData = {
username: 'jackie'
};
//the URL where we'll send the AJAX request
var url = '/Home/UsernameExists';
//make the AJAX call over POST
$.post({
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(requestData),
url: url,
error:function () {
alert('Sorry, an error occurred. Please try again later.');
},
success: function(response) {
alert(response.exists); //this will alert "true" if the user exists
}
});
});
The UsernameExists method below is where the JSON request is read, and where the JSON response is returned. The other method just renders the page from which the request occurs (see the CherryPy MVC article for context).
import cherrypy
from controllers.base import BaseController
class HomeController(BaseController):
@cherrypy.expose
def index(self):
return self.render_template('home/index.html')
@cherrypy.expose()
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def UsernameExists(self):
json_obj = cherrypy.request.json
usernames = ['bruce', 'lee', 'jackie', 'chan']
return {"exists": json_obj['username'] in usernames}
CherryPy JSON Tools Documentation
How to receive JSON in a POST Request
Leave a comment