简体   繁体   English

在Flask应用中将变量从后端传递到前端

[英]Passing a variable from the backend to the frontend in a Flask app

Basically I want the code below to put the "search" from the backend to the frontend. 基本上,我希望下面的代码将“搜索”从后端放到前端。

I am having trouble getting my flask app to pass data from the back end to the front end using templates and a simple flask structure. 我无法让我的flask应用程序使用模板和简单的flask结构将数据从后端传递到前端。

I am open to suggestions for better ways. 我愿意提出更好的建议。 Also @ Daniel Mesejo has been a great help so far in my learning about Flask and ajax/jquery. 到目前为止,@ Daniel Mesejo在我对Flask和Ajax / jquery的学习中也提供了很大的帮助。

here is my app.py 这是我的app.py

from scraper import scrape
from flask import Flask, render_template, jsonify, make_response, request
import json
app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def index():

    entries = json.dumps(scrape("video games"))
    return render_template('index.html', entries= entries)

@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data():
    if request.method == "POST":
        #data = request.form("blah")
        #print("blah")
        search = request.get_json()
        #new_search = json.dumps(scrape(data))
        return jsonify(search)
    return render_template('index.html')

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=5000)

here is my index.html 这是我的index.html

<!DOCTYPE html>
<html>

<head>
    <title>Flask app</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

  </head>
<body>

  <div class="topnav">
    <a class="active" href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
    <form class = "form" action="" method="POST">
      <input id ="textbox" name="textbox" type="text" placeholder="Search..">
      <button type="submit">submit</button>
    </form>
  </div>

  <p>you searched: {{search}} </p>

  <div id="div1">
  <p id="p1"></p>
  <p id="p2"></p>
  </div>

<script>

var value = $('.textbox').val();
//alert(value);
$("button").click(function (e) {
    e.preventDefault();
    var value = $("#textbox").val();
    alert(value);
    $.ajax({
      type: 'POST',
      url: "parse_data",
      data: JSON.stringify({"text" : value}),
      contentType: 'application/json; charset=utf-8',
      success: function(data){
        alert(JSON.stringify(data));
      }
    });
});


var jsonz = {{ entries|tojson }};



var s = JSON.parse(jsonz);



var i;
for (i = 0; i < s.length; i++) {
  var para = document.createElement("p");
  var node = document.createTextNode(s[i].product_name + "\n" + s[i].product_link);
  para.appendChild(node);

  var element = document.getElementById("div1");
  element.appendChild(para);
}




//document.getElementById("user").innerHTML =
//obj;
//"Name: " + obj.product_name + "<br>" +
//"Location: " + obj.product_link;
</script>



</body>
</html>

To achieve want that simply change the function you pass to success like this: 要实现这一目标,只需更改传递给success的函数,如下所示:

success: function (data) {
                $("#search-query").text("you search: " + data["text"]);
            }

and change the <p> element to <p id="search-query"> you searched: </p> . 并将<p>元素更改为<p id="search-query"> you searched: </p>

To learn more about Flask and web development in general I suggest the Flask Mega Tutorial, in here . 要总体上了解有关Flask和Web开发的更多信息,请在此处提出Flask Mega教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM