[英]Dynamic Loading on Flask Site with Unique URL
I am building a Flask site that dynamically loads some information like the time but I'm running into some issue with AJAX with jQuery.我正在构建一个 Flask 站点,它动态加载一些信息,比如时间,但我遇到了一些关于 AJAX 和 jQuery 的问题。
Following the example on the flask site https://flask.palletsprojects.com/en/1.1.x/patterns/jquery/按照flask 站点上的示例https://flask.palletsprojects.com/en/1.1.x/patterns/jquery/
I want to change it to a dynamic URL based on the users unique ID instead of a static one.我想将其更改为基于用户唯一 ID而不是静态 URL 的动态 URL。
Python File: Python文件:
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/_add_numbers/<UNIQUEID>')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
@app.route('/')
def index():
return render_template('index.html')
The HTML HTML
<script type=text/javascript>
$(function() {
$('a#calculate').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/_add_numbers/UNIQUEID', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
<h1>jQuery Example</h1>
<p><input type=text size=5 name=a> +
<input type=text size=5 name=b> =
<span id=result>?</span>
<p><a href=# id=calculate>calculate server side</a>
I cannot figure out how to put a unique ID into the HTML.我不知道如何将唯一 ID 放入 HTML。 Any help is much appreciated!任何帮助深表感谢!
There are a variety of ways to do this.有多种方法可以做到这一点。 I would recommend simply adding the user's id into the template context, with render_template("index.html", user_id=current_user.id)
(make sure you import current_user
from flask. This will return a user id if the user is logged in, and None
if not. Then you can do the following:我建议简单地将用户的 id 添加到模板上下文中,使用render_template("index.html", user_id=current_user.id)
(确保您从烧瓶中导入current_user
。如果用户登录,这将返回用户 id,并None
。如果没有,那么你可以做到以下几点:
$(function() {
$("a#calculate").bind("click", function() {
$.getJSON($SCRIPT_ROOT + "/_add_numbers/{{ user_id }}",
etc etc: your code goes here
)}
)}
That should do it.那应该这样做。
Alternatively you could actually use the value of current_user.id
(if you feel you understand it) in the template, as this is implicitly passed down with Jinja anyway.或者,您实际上可以在模板中使用current_user.id
的值(如果您觉得您理解它),因为无论如何它都隐式地通过 Jinja 传递了下来。 o substitute {{ user_id }}
with `{{ current_user.id }}. o 将{{ user_id }}
替换为 `{{ current_user.id }}。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.