简体   繁体   English

在不重新加载页面的情况下从 Javascript → Python 发送数据并返回

[英]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。

TL;DR长话短说

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.

相关问题 发送GET变量而无需使用javascript重新加载页面 - Send GET variables without reloading the page with javascript 通过cURL发送数据而无需重新加载页面 - Send data via cURL without reloading page 需要访问使用php输入到表单中的数据,然后将其发送到javascript,并且都在同一页面上而无需重新加载吗? - Need to access data entered into a form using php and then send it to javascript all on the same page and without reloading? 从服务器接收ajax回调中的数据,而无需重新加载并更新当前页面。 Express 4和节点 - Receive data in ajax call back from server without reloading and update current page. Express 4 and Node 从数据库删除数据而无需重新加载页面 - Delete data from database without reloading the page 如何使用Ajax发送数据而无需重新加载页面? (Node.js) - How to send data with ajax, without reloading page? (Nodejs) 如何在不重新加载页面的情况下将数据javascript传递到php页面 - how to pass data javascript into php page without reloading the page 如何在不重新加载页面的情况下将值从 controller 发送到 ejs:Nodejs - How to send value from controller to ejs without reloading page : Nodejs 从php获取json数据而无需重新加载 - Getting json data back from php without reloading 从asp.net数据表中重新加载javascript数据元素,而无需重新加载页面 - Reload a javascript data element from asp.net datatable without reloading the page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM