SoFunction
Updated on 2024-11-17

Python Flask front-end and back-end Ajax interaction method example

Previously summarized the basics in the flask, now to summarize the flask in the front and back end of the knowledge of data interaction, here with the Ajax

I. Post methodology

1, the location of the post method: in the front-end HTML, bound to a button click function, or a mouse input box click to leave the event.

(1) Data is attached to the URL (request path) and sent to the backend.

/* Front-end HTML<script>in:*/
$.post("/js_post/"+ip, data_to_backend, function(data){alert("success "+data)} );

where ip, data_to_backend are defined before this code; data_to_backend is generally a json data(data_to_backend={'ip':$(this).parent().prev().text()})and data is the return data from the backend.

# In the backend py file (the py file for the html before the route is launched): add a route to handle the frontend post requests.
@("/js_post/<ip>", methods=['GET', 'POST'])
def js_post(ip):
   print ip
   return ip +" - ip"

The effect after clicking the button:

Front-end definition of popup data

ip in the URL

(2) Data is sent to the back-end separately

var ip = $(this).parent().prev().prev().prev().prev().text();
data_tmp = {'ip':ip, 'text':"success for ajax"};  // data to send to server.
$.post('/js_call', data_tmp, function(data){alert(data)});

Backend Handler:

@('/js_call', methods=['GET', 'POST'])
def js_call():  
   print ['ip']  
   print ['text']  
   # to send the command by ssh : ("ssh user@host \' restart(command) \' ")  
   return 'ok!!!!'

post independent data sending

Second, get method (the same can send data)

$.get('/js_get', {'method':'GET', 'text':"from-html"}, function(data){alert(data)})

The back-end routes receive the processing:

@('/js_get', methods=['GET'])
def js_get():
  print "method: "+['method']+" --- text: "+['text']
  return "get success!"

get success

Data received successfully

Note that: one of the backend py files is similar to the['method']The request that gets the data is a Python flask module that needs to be imported.

Summary:

  • In the flask framework, Ajax request for the back-end can be easily implemented, just in the back-end Python code on the ajax path processing can be.
  • Ajax's post, get methods can send data to the background, just generally use post to send data (to make changes), get request data (do not change).

This is the whole content of this article.