I try and create general javascript functions for submitting to my server. And then create functions for creating the JSON objects I pass.
I create an object in javascript, put values in it, then send it via ajax to my tornado server
if test it a bit(could be more diligent) then i just turn it into a regular dict object in python. i do some stuff, then send back a json response saying "we're all good"
PYTHON TORNADO HANDLER:
class AddRoleHandler( tornado.web.RequestHandler ):
def post(self):
role = self.get_argument("role", None)
if role:
global ecs
role = json.loads( role );
result = ecs.add_role( role["name"], role["description"], role["keys"], role["uuid"] )
self.write(json.dumps({"msg":"role saved"}))
JAVASCRIPT:
submitRequest = function( req_obj, api_call, _callback ) {
if( typeof req_obj == "object" ) {
$.ajax({
type: "POST",
url: "/" + api_call,
data: {"role": JSON.stringify(req_obj)},
dataType: 'json',
success: _callback
});
}
}
roleAdded = function( data ) {
console.log( data );
window.location.reload( true );
}
addRole = function( ) {
var role = {}
role['name'] = $("#role_name").val();
role['description'] = $("#role_desc").val();
role['keys'] = [];
role['uuid'] = ecs.uuid();
$.each( $("#sending_keys input"), function(index,value) {
role['keys'].push( $(value).val() );
});
submitRequest( role, "addrole", roleAdded );
> I think the clue can be found by 'X-Requested-With' in request header.
>
> In tornado, maybe you can get this by
>
> self.request.headers.get('X-Requested-With')
>
> Please let me know if there is a better way.
I am using exactly this base on the `is_ajax` method in Django:
def is_ajax(self):
return "X-Requested-With" in self.request.headers and \
self.request.headers['X-Requested-With'] == "XMLHttpRequest"
Hth,
Daniel