简体   繁体   中英

Flask GET and POST request: APIS

This my first time working with an api that returns a result. So I am using a post request to get information from the user in a form:

<form action="{{url_for('international.get_grade_data')}}"  method="POST">
........
</form>

the endpoint looks like this:

@international.route("/grade_data", methods=["GET", "POST"])    
@tfa_login_required    
def get_grade_data():
    if request.method == "POST":
       grading_system_from= request.form.get('country_from')
       grading_system_to = request.form.get('country_to')
       users_grade= request.form.get('user_grade')
       grade_request= {"free_grade": users_grade, "country_to": grading_system_to, "country_from": grading_system_from} 
       grade= grade_comparison_tool(grade_request)
       return jsonify(
        grade_request = grade
       )

This data is sent to an api and then returns a result in JSON.

but when the user clicks on the submit button the user gets redirected to the json result.

I would like to get the result in the URL and then display the result on the webpage without redirect to the json result. How do I achieve this? I have gone online to know about POST and GET but not still clear.

Regarding the question I have been able to find a solution by changing the strategy, firstly, I prevented the default action of the form:

<form action="#" onsubmit="return false"  method="POST">
........
</form>

secondly, in the JS file I used an AJAX call to send the data from the form and received the result back in a click event:

function dataLoading(){
    let datasetDict = {
    "free_grade": free_grade.value,
    "country_from": countryFrom.value,
    "country_to": countryTo.value
}
$.ajax({
  type: "POST",
  url: '/international/grade_data',
  data: JSON.stringify(datasetDict),
  success: function(data_result, status){
     console.log( JSON.stringify(data_result) + ': ' + status)
  },
  contentType: 'application/json;charset=UTF-8',
  dataType: 'json' 
});
}

document.getElementById('convert-button').addEventListener('click', dataLoading)

modified the flask python code:

@international.route("/grade_data", methods=["POST"])    
@tfa_login_required    
def get_grade_data():
    if request.method == "POST":
        user_grade_data =request.get_json()
        grade = grade_analy(user_grade_data)
        return jsonify(grade)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM