简体   繁体   中英

Send variable from JavaScript into Flask

I'm a complete beginner here and facing a problem in passing javascript variable into flask. Please note that my question is completely 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!

The 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.

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