[英]Flask GET and POST request: APIS
This my first time working with an api that returns a result.这是我第一次使用返回结果的 api。 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.该数据被发送到 api,然后在 JSON 中返回结果。
but when the user clicks on the submit button the user gets redirected to the json result.但是当用户点击提交按钮时,用户会被重定向到 json 结果。
I would like to get the result in the URL and then display the result on the webpage without redirect to the json result.我想在 URL 中得到结果,然后在网页上显示结果而不重定向到 json 结果。 How do I achieve this?
我如何实现这一目标? I have gone online to know about POST and GET but not still clear.
我已经上网了解 POST 和 GET 但仍不清楚。
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:其次,在 JS 文件中,我使用了 AJAX 调用从表单发送数据并在点击事件中接收结果:
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:修改flask python代码:
@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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.