[英]Send data from Javascript → Python and back without reloading the page
I'm trying to make a stock finance like website where anyone can get fake money and buy stocks.我正在尝试制作一个类似网站的股票金融网站,任何人都可以在其中获得假钱和购买股票。 So in the buy page, I am trying to implement a feature where as the user types the stock symbol and the number of shares, in real time, the pricing shows up in the h1 tags that have an id of "render".因此,在购买页面中,我尝试实现一项功能,当用户键入股票代码和股票数量时,价格会实时显示在 ID 为“render”的 h1 标签中。 This can be achived if user input is sent to my app.py
and after looking up the price using an api and some math, app.py
send the price back to javascript to update the page.如果将用户输入发送到我的app.py
并在使用 api 和一些数学查找价格后, app.py
将价格发送回 javascript 以更新页面,则可以实现这一点。 I've been trying to use fetch()
and AJAX
but I don't understand any of the tutorials or stack overflow questions.我一直在尝试使用fetch()
和AJAX
,但我不理解任何教程或堆栈溢出问题。 Can someone give me a reliable solution and explain it to me?有人可以给我一个可靠的解决方案并向我解释吗?
HTML: HTML:
{% extends "layout.html" %}
{% block title %}Buy{% endblock %}
{% block main %}
<form action="/buy" method="post">
<div class="mb-3">
<input class="form-control mx-auto w-auto" autocomplete="off" name="symbol" placeholder="Symbol" value="{{ input_value }}" id="symbols">
</div>
<div class="mb-3">
<input class="form-control mx-auto w-auto" autocomplete="off" autofocus name="shares" placeholder="Shares" id="shares">
</div>
<div class="mb-3">
<button class="btn btn-primary" type="submit">Buy</button>
</div>
</form>
<h1 id="render">
</h1>
<script>
</script>
{% endblock %}
App.py:应用程序.py:
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
if request.method == "GET":
return render_template("buy.html", input_value = "")
else:
return render_template("buy.html", input_value = request.form.get("symbol"))
I'm trying to use the function above for rendering the template我正在尝试使用上面的函数来呈现模板
Accepting response and sending back information:接受响应并发回信息:
@app.route("/show_price", methods=["GET", "POST"])
def show_price():
#logic stuff
return #price
TL;DR at bottom TL;底部的DR
I found a solution to the problem by using this as my app.py:我通过将其用作我的 app.py 找到了解决问题的方法:
@app.route("/show_price", methods=["GET", "POST"])
@login_required
def show_price():
# https://www.makeuseof.com/tag/python-javascript-communicate-json/
data = request.get_json()
if data[1].isdigit() == True:
data = jsonify() # the data
return data
else:
return ""
and using fetch() in my javascript:并在我的 javascript 中使用 fetch():
{% extends "layout.html" %}
{% block title %}Buy{% endblock %}
{% block main %}
<form action="/buy" method="post">
<div class="mb-3">
<input id="symbols">
</div>
<div class="mb-3">
<input id="shares">
</div>
<h2 id="render">
</h2>
<div class="mb-3">
<button class="btn btn-primary" type="submit">Buy</button>
</div>
</form>
<script>
let input1 = document.getElementById('symbols');
let input = document.getElementById('shares');
input.addEventListener('keyup', function(event) {
value = [
input1.value, input.value
]
fetch("http://127.0.0.1:5000/show_price",
{
method: 'POST',
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(value)}).then(res =>{
if(res.ok){
return res.json()
} else {
document.querySelector('h2').innerHTML = "Keep typing...";
}
}).then(jsonResponse=>{
word = "That would be " + jsonResponse
document.querySelector('h2').innerHTML = word;
})
.catch((err) => console.error(err));
});
</script>
{% endblock %}
so as the user is typing in the the shares field the event listener will get the symbols and shares fields, use fetch() to get the data over to def show_price() with a jsonified array of symbol and shares.因此,当用户在 shares 字段中输入时,事件侦听器将获取符号和 shares 字段,使用 fetch() 将数据传递给 def show_price() 以及符号和股票的 jsonified 数组。 If there is an error the div id="render" will display "Keep typing".如果出现错误,div id="render" 将显示“继续输入”。 After python gets the information it will look it up using a function, then it will return the price of the shares in json format. python 获取信息后,它会使用一个函数查找它,然后它会返回 json 格式的股票价格。 Then javascript will get the data and use some javascript to change the html.然后 javascript 将获取数据并使用一些 javascript 来更改 html。
Basically I used fetch() to get the data to python, did some algorithm stuff and python return it to javascript.基本上我使用 fetch() 将数据获取到 python,做了一些算法,然后 python 将它返回给 javascript。 https://www.makeuseof.com/tag/python-javascript-communicate-json/ is really useful in teaching you how to use fetch(). https://www.makeuseof.com/tag/python-javascript-communicate-json/在教你如何使用 fetch() 方面真的很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.