I'm a plete beginner here and facing a problem in passing javascript variable into flask. Please note that my question is pletely different from previous question that has been asked.
This is my code:
JavaScript
var dd = {'mvar': 1};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/",
data: JSON.stringify(dd),
success: function (data) {
alert("DONE!")
},
dataType: "json"
});
Flask(edited)
@app.route('/', methods=['GET', 'POST'])
def new():
form = InputForm(request.form)
v = request.get_json().get('mvar')
print(v)
return render_template('new.html',form=form,v=v)
However, when the output that I get when print out the result is "None" while I expected it to be "1"
Really hope that experts can help me, thank you!
I'm a plete beginner here and facing a problem in passing javascript variable into flask. Please note that my question is pletely different from previous question that has been asked.
This is my code:
JavaScript
var dd = {'mvar': 1};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/",
data: JSON.stringify(dd),
success: function (data) {
alert("DONE!")
},
dataType: "json"
});
Flask(edited)
@app.route('/', methods=['GET', 'POST'])
def new():
form = InputForm(request.form)
v = request.get_json().get('mvar')
print(v)
return render_template('new.html',form=form,v=v)
However, when the output that I get when print out the result is "None" while I expected it to be "1"
Really hope that experts can help me, thank you!
Share Improve this question edited Aug 3, 2017 at 5:15 iyzad asked Aug 3, 2017 at 1:43 iyzadiyzad 812 gold badges2 silver badges10 bronze badges 4-
You can using javascript set value of
mvar
to session and get value of session in flask – tuannv256 Commented Aug 3, 2017 at 2:01 - Can you teach me how to do it? I did not learn on session yet – iyzad Commented Aug 3, 2017 at 2:04
- I'm not good at JavaScript. Do you know how to set session variable like this. To get session variable in Flask, refer Flask session – tuannv256 Commented Aug 3, 2017 at 2:58
- I'm not sure how it gonna be – iyzad Commented Aug 3, 2017 at 3:00
2 Answers
Reset to default 2The Request.get_json() method is what you are looking for in your Flask code.
data = request.get_json()
edit here is the exact pattern i use which works:
javascript:
$.ajax({
type: "POST",
url: "{{ url_for("get_post_json") }}",
contentType: "application/json",
data: JSON.stringify({hello: "world"}),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});
python:
@app.route('/_get_post_json/', methods=['POST'])
def get_post_json():
data = request.get_json()
return jsonify(status="success", data=data)
Instead of using
v = request.form.get('mvar', type=int)
Use this
v = request.get_json().get('mvar')
Once you print v then you should get it.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745615262a4636196.html
评论列表(0条)