【问题标题】:GET data from HTML and process in python using Flask and POST back in same HTML使用 Flask 从 HTML 获取数据并在 python 中处理,然后在相同的 HTML 中返回
【发布时间】:2017-03-14 14:25:01
【问题描述】:

您好,我正在尝试实现聊天类型模块。我的前端在一个 HTML 页面中,我从中获取数据。将获得的数据传递给 python flask。最后,处理后的数据必须回传到同一个 HTML 页面。

我能够获取数据。但无法将其发布回同一 HTML 页面。

以下是HTML代码

<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function ajaxcall(){
var p_name = $('#p_name').val();
var p_email = $('#p_email').val();

  $.post("http://127.0.0.1:5000/getdata?chatbox="+p_name);
  }
</script>
</head>
<form action="" method="POST" name='chat'>
    <div>
    {{text_typed}}
    </div>
    Enter Chat: <textarea id="p_name" name="chatbox" rows="4" cols="50"></textarea>
    <input type="button" onclick="ajaxcall()" value="submit me!" />
    <label name='get_test' id='get_test'></label>
</form>
</html>

在文本区域输入的值必须张贴在 {{text_typed}} 中。我无法得到这个

这是我的 python 烧瓶编码 [我在本地环境中执行此操作]

from flask import Flask, jsonify, request, render_template, flash, url_for, redirect #import objects from the Flask model
app = Flask(__name__) #define app using Flask

@app.route('/')
def hello():
    print("hello")
    return "Welcome to mychat.in"

@app.route('/chat', methods=['GET', 'POST'])
def chat():
    return render_template("getpost.html")

@app.route('/getdata', methods=['GET', 'POST'])
def getdata():
    print('hi')
    text_typed = request.args.get('chatbox')
    print(text_typed)        
    return render_template("getpost.html", text_typed = text_typed)# this is the line i am trying to post back in html

if __name__ == '__main__':
    app.run()

提前致谢。

【问题讨论】:

    标签: html python-3.x flask


    【解决方案1】:

    更新你的 JS 代码:

    $.post("http://127.0.0.1:5000/getdata?chatbox="+p_name);
    

    根据jQuery documentation你应该把它写成

    $.post("http://127.0.0.1:5000/getdata?chatbox="+p_name, null, function(data) {
    Put your code to insert returned _data_ into the form here. 
    });
    

    【讨论】:

      猜你喜欢
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 2021-05-17
      • 2014-08-13
      • 1970-01-01
      相关资源
      最近更新 更多