将 JavaScript 变量传递给 Flask url_for [英] Pass JavaScript variable to Flask url_for

查看:36
本文介绍了将 JavaScript 变量传递给 Flask url_for的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个端点,它接受 url 中的一个值并生成一些将插入到 div 中的内容.我想使用 JavaScript 变量用 url_for 构建 url.但是,$variable1 是作为字符串传递的,而不是 variable1 的值.如何将 JavaScript 变量的值传递给 url_for?

I have an endpoint that takes a value in the url and produces some content that will be inserted into a div. I want to build the url with url_for using a JavaScript variable. However, $variable1 is passed as a string, rather than the value of variable1. How can I pass the value of a JavaScript variable to url_for?

function myFunction() {
    var variable1 = "someString"
    $('#demo').load(
        "{{ url_for('addshare2', share = '$variable1') }}"
    );
}

推荐答案

您无法在 Jinja 中评估 JavaScript.您正在尝试在 Jinja 呈现时在服务器端生成一个 url,但您引用的变量仅在客户端浏览器上运行的 JavaScript 中可用.

You can't evaluate JavaScript in Jinja. You're trying to generate a url on the server side while Jinja is rendering, but you're referencing a variable that is only available in the JavaScript running on the client browser.

在客户端构建 url 是最直接的解决方法.(我不知道你的路线是什么样的,所以这是一个例子.)

Building the url on the client side is the most straightforward fix. (I don't know what your route looks like, so here's an example.)

$('#demo').load('/url/for/addshare2/' + variable1);

然而,这不是很有用,因为你不能使用 url_for,所以你必须对 url 进行硬编码.这是一个好兆头,表明您想要的是一个向其传递参数的 AJAX 端点,而不是包含值的端点.

However, this isn't very useful because you can't use url_for, so you have to hard-code the urls. This is a good sign that what you want is an AJAX endpoint that you pass parameters to, rather than an endpoint that contains values.

@app.route('/addshare2', methods=['POST'])
def addshare2():
    share = request.json['share']
    ...
    return jsonify(result=...)

现在你可以用url_for生成url,并将参数作为表单数据传递.

Now you can generate the url with url_for, and pass the parameters as form data.

$.post(
    '{{ url_for('addshare2') }}',
    {share: variable1},
    function (data) {
        // do something with data on successful response
    }
);

这篇关于将 JavaScript 变量传递给 Flask url_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆