Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将JavaScript变量值传递到python变量(flask)_Javascript_Python_Html_Flask - Fatal编程技术网

如何将JavaScript变量值传递到python变量(flask)

如何将JavaScript变量值传递到python变量(flask),javascript,python,html,flask,Javascript,Python,Html,Flask,我想在python变量中发送这个变量值以执行不同的任务 var d="string" 我不想通过URL发送变量值。 我想用一些像这样的代码 @app.route("/", methods=['POST']) def hello1(): d = request.form['n'] #here i take value from name of html element 使用AJAX帖子 let myVar = 'Hello' $.post('http://localhost:5000/

我想在python变量中发送这个变量值以执行不同的任务

var d="string"
我不想通过URL发送变量值。 我想用一些像这样的代码

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

let myVar = 'Hello'
$.post('http://localhost:5000/getjs', {myVar}, function(){
    // Do something once posted.
})
你的烧瓶是这样的

@app.route('/getjs', methods=['POST'])
def get_js():
    if request.method == 'post':
        js_variable = request.form
        return js_variable
或者,您可以执行以下操作:

@app.route('/getjs/<variable>')
    def get_js(variable):
        js_variable = variable
        return js_variable
@app.route('/getjs/'))
def get_js(变量):
js_变量=变量
返回js_变量
所以当你把你的url指向
js_变量将是“apples”

使用本机javascript“fetch”

Ari Victor的解决方案需要一个外部库: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));

例如,您可以通过表单或ajax callfixed发送它。这只是我的一个想法,但我使用它的方法将数据从JS发送到后端FlaskyYou真的应该使用jsonify将响应返回到ajax调用中。看,我们不是来牵手的,只是给人们指出正确的方向。那么请提供一个答案,这就是问题的关键,不是吗?