Ajax, refers to the Web page asynchronous refresh, the general implementation of the JS code to the server post request, and then return the results received on the page.
Here I write a simple page, ajax.html
<HTML><Head> <title>Test Ajax</title> <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /> <Scriptsrc= "Http://code.jquery.com/jquery-1.9.1.min.js"></Script> <styletype= "Text/css">#result{Border:10px;font-size:50px;background:#ff0fef;} </style></Head><Body> <inputtype= "text"ID= "word" > <BR> <ButtonID= "Foo">Click</Button> <DivID= "Result"> </Div><Scripttype= "Text/javascript"> $("#foo"). Click (function() { varWord= $("#word"). Val (); //get the input of a text box //Send word to the background PHP program //The returned data is placed in the status$.post ("/test", {Message:word},function(data,status) {if(Status== "Success") { $("#result"). HTML (data); } Else{alert ("Ajax Failure"); } }); });</Script></Body></HTML>
Note that the data is stored in the "message" field, as you can see from the code above.
So the background parsing data from the message, we remember is the Get_argument method.
So the python code behind the scenes is:
ImportTornado.ioloopImportTornado.webclassMainHandler (tornado.web.RequestHandler):defGet (self): Self.render ("ajax.html")classAjaxhandler (tornado.web.RequestHandler):defpost (self):#self.write ("Hello World")Self.write (Self.get_argument ("message")) Application=Tornado.web.Application ([(R"/", MainHandler), (R"/test", Ajaxhandler),])if __name__=='__main__': Application.listen (8888) tornado.ioloop.IOLoop.instance (). Start ()Visit the homepage and render the Ajax front-end page, while Ajaxhandler handles the real Ajax asynchronous request.
Here is a summary of the process:
1. Users visit home page, Tornado use MainHandler to return to ajax.html page
2. The user fills in the information, clicks the button, because before the loading JS code, registers the callback function, therefore triggers the Ajax
3.js posts a POST request to the background.
4. Use Ajaxhandler to process the post request based on the requested Url,tornado and return the information as it is.
5.js receives the data, invokes the previous callback function, and displays the results on the HTML page.
Implementing AJAX requests with Tornado