简体   繁体   中英

how to pass JavaScript variable value into python variable(flask)

I want to send this variable value in python variable to perform different tasks.

var d="string"

I don't want to send variable values through URL. I want to use some like this code.

@app.route("/", methods=['POST'])
def hello1():
    d = request.form['n'] #here i take value from name of html element

use an AJAX post.

let myVar = 'Hello'
$.post('http://localhost:5000/getjs', {myVar}, function(){
    // Do something once posted.
})

and your Flask will be something like this

@app.route('/getjs', methods=['POST'])
def get_js():
    if request.method == 'post':
        js_variable = request.form
        return js_variable

Alternatively you can do this:

@app.route('/getjs/<variable>')
    def get_js(variable):
        js_variable = variable
        return js_variable

so when you direct your url to http://localhost:5000/getjs/apples js_variable will be 'apples'

Use native javascript 'fetch'.

Ari Victor's solution requires an external library: jquery

var url = 'http://localhost:5000/getjs';
var data = {field_name: 'field_value'};

fetch(url, {
  method: 'POST',
  body: JSON.stringify(data), 
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

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