This article describes how to handle AJAX requests,
One, the POST request to process Ajax
Example one:
JS code examples are as follows:
var id = obj.parentNode.parentNode.id; $.post (function(data) { showData (data); },"JSON");
An example of the corresponding flask code is as follows:
@app. Route ('/delitem/<id>', methods=['POST') def delitem (ID): # business code # Db.data is a Python list object (the element is a dictionary) and is returned to the browser as a JS array (the element is the Josn object return jsonify ({"result ":d B.data})
Example 2:
JS code is as follows
var id = $ ("#recordid"). Val (); var name = $ ("#recordname"). Val (); var msg = $ ("#recordinfo"). Val (); $.post (function(data) { showData (data); },"JSON");
The corresponding flask code is as follows:
@app. Route ('/additem', methods=['POST'])defadditem (): Db.additem (Request.form.get ('ID'), Request.form.get ('name'), Request.form.get ('msg')) returnJsonify ({"result":d B.data})
Note that you need to specify the methods parameter as post in the @app. Route method
As you can see, in flask, the request is made through Request.form.get to get Ajax. The Get method can also take the 2nd parameter default value, and if the specified parameter name does not exist, the default value is returned, and none is returned. Note that if the browser is not a POST request through Ajax, but rather is submitted through a form, use the request.form[form element name] to get the value in the form element .
Second, get requests to process Ajax
Similar to the POST request, the difference is:
1) @app. The methods parameter is not required in the route method because the default is to respond to a GET request
2) to get the parameters of JS sent by the Request.args.get method
Flask Web development Processing AJAX requests