Flask Web development Processing AJAX requests

Source: Internet
Author: User
Tags python list

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.