JavaScript
client sending request like this:
$.ajax({
url: 'http://localhost:7973/test',
type: 'GET',
data: {'host': 'mike', 'guests': {'name': ['car', 'ball'], 'age': [6, 10, 7]}},
success: function(result){alert(result)},
error: function(error){alert(error)}
});
Python
server handling request using tornado
:
import tornado.ioloop
import tornado.web
class TestHandler(tornado.web.RequestHandler):
def get(self):
host = self.get_argument('host')
print(host)
guests = self.get_argument('guests')
print(guests)
def make_app():
return tornado.web.Application([
(r'/test', TestHandler)
])
if __name__ == "__main__":
app = make_app()
port = 7973
app.listen(port)
print('-' * 100)
print('server started, listening to ', port, '...\n')
tornado.ioloop.IOLoop.current().start()
The outputs on the server side is as below. Apparently, the 'host' argument is successfully got, but I have no clue how to get a argument whose value is a complex object itself (say an array or a dictionary). Please explain to me the mechanism of these casts and dumps between data structures and their string representation? I read the tornado document, but I'm not able to find the answer.
mike
WARNING:tornado.general:400 GET /test?host=mike&guests%5Bname%5D%5B%5D=car&guests%5Bname%5D%5B%5D=ball&guests%5Bage%5D%5B%5D=6&guests%5Bage%5D%5B%5D=10&guests%5Bage%5D%5B%5D=7 (::1): Missing argument guests
WARNING:tornado.access:400 GET /test?host=mike&guests%5Bname%5D%5B%5D=car&guests%5Bname%5D%5B%5D=ball&guests%5Bage%5D%5B%5D=6&guests%5Bage%5D%5B%5D=10&guests%5Bage%5D%5B%5D=7 (::1) 1.99ms
You can convert your json object to a json string.
change
data: {'host': 'mike', 'guests': {'name': ['car', 'ball'], 'age': [6, 10, 7]}},
to
data: JASON.stringify({'host': 'mike',
'guests': {'name': ['car', 'ball'],
'age': [6, 10, 7]}}),
and then on the server side you can do:
guests_string = self.get_argument('guests')
guests = json.loads(guests_string)
guests
should be a dictionary that you can do whatever with in Python.