简体   繁体   English

为什么我不能从 flask html 向 flask Z23EEEB4347BDD26BDDFC6B7EE 发送消息?

[英]why can't I send messages from flask html to flask python?

I have been working on a program in flask that allows you to search a database.我一直在研究 flask 中的一个程序,该程序允许您搜索数据库。 I have not coded the actual finding stuff in the data base or anything but I don't need that right now, and the database does not effect anything right now.我没有对数据库中的实际查找内容或任何内容进行编码,但我现在不需要,并且数据库现在不会影响任何内容。 I have not been able to get past how to get what the user types in the form to the python program.我无法理解如何将用户在表格中输入的内容输入到 python 程序中。 It runs with no errors but when I check what I received I get None.它运行没有错误,但是当我检查收到的内容时,我得到了无。 Is there something I'm doing wrong?有什么我做错了吗? This is my code, it is very messy and just one file.这是我的代码,非常混乱,只有一个文件。

main.py主文件

from flask import Flask, render_template
from flask import request
import pdfkit, time




def go(letters):
  data = open('data.txt','r')
  return letters
  
   
app = Flask(__name__)
       
@app.route("/path/", methods=['GET','POST'])
def search():
  time.sleep(1)
  data=request.get_data()
  print(data)
  return go(data)

@app.route('/')
def index():
  
  return render_template('index.html')

if __name__ == "__main__":
    from waitress import serve
    serve(app, host="0.0.0.0", port=8080)
    app.run(debug=True)

templates/index.html模板/索引.html

<!Doctype html!>

<html land=en>
<h1>Welcome!</h1><br>
<p>Type to search the database.</p>
<br><form name='this' onsubmit='letsgo()' class='text' action='/path/' method='post'><input id='hey' type='text'> <input type='submit' value='search'></form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var test = document.getElementById('hey').value;
  const xhr = new XMLHttpRequest();
function letsgo() { 
  
  const data = document.getElementById("hey").value
  alert(data)
$.ajax({
  type : 'POST',
  url : "{{'https://file-encrypter.ashwinchera.repl.co/path/'}}",
  dataType: 'data',
  datas : {'data':data}
});
            

};      
</script>

also I am working with a friend, so I don't know what some of this stuff is here for.我也在和一个朋友一起工作,所以我不知道这些东西是用来做什么的。 Can someone tell me how I can send this data?有人可以告诉我如何发送这些数据吗? I have been trying things from other questions, but they don't work.我一直在尝试其他问题,但它们不起作用。 Thank you in advance!先感谢您!

There are multiple issues here.这里有多个问题。 As mentioned in the comments, I recommend working slowly and breaking the problem down into small pieces.正如评论中提到的,我建议慢慢地工作并将问题分解成小块。 Check that each piece works before rushing ahead and accumulating many errors that are hard to unravel.在匆忙前进并积累许多难以解决的错误之前,请检查每件作品是否有效。

Most of the problems are on the front-end, so you'll want to use the browser console to inspect errors.大多数问题都在前端,因此您需要使用浏览器控制台来检查错误。 You can also use an HTML validator tool to make sure your HTML makes sense and catches typos like land=en .您还可以使用HTML 验证器工具来确保您的 HTML 有意义并捕获诸如land=en之类的拼写错误。

Since it sounds like you want to POST without a page refresh and you're using jQuery, many properties on your form are unnecessary:由于听起来您想在不刷新页面的情况下发布并且您正在使用 jQuery,因此表单上的许多属性都是不必要的:

onsubmit='letsgo()' action='/path/' method='post'

can all be removed.都可以去掉。 While you're at it, remove any unused noise like:当您使用它时,请删除任何未使用的噪音,例如:

var test = document.getElementById('hey').value;
  const xhr = new XMLHttpRequest();

and unnecessary ids and classes.和不必要的 ids 和 classes。 These are just adding to the confusion.这些只是增加了混乱。 When things don't make sense and aren't working, try stripping out code rather than adding it.当事情没有意义并且不起作用时,请尝试剥离代码而不是添加代码。

"{{'https://file-encrypter.ashwinchera.repl.co/path/'}}" should just be /path so that it'll work on any domain such as a localhost. "{{'https://file-encrypter.ashwinchera.repl.co/path/'}}"应该只是/path以便它可以在任何域(例如本地主机)上工作。 If you're working cross-origin, that's another story, but I don't think you are.如果你在跨域工作,那就是另一回事了,但我不认为你是。

In the $.ajax call, datas is a typo.$.ajax调用中, datas是一个错字。 That should be data .那应该是data

const data = document.getElementById("hey").value isn't necessary. const data = document.getElementById("hey").value不是必需的。 If you're bothering to import jQuery, you might as well use it all the way: $("#hey").val() .如果你懒得导入 jQuery,你不妨一直使用它: $("#hey").val() #hey and letsgo are unclear names that don't make it any easier to debug the app. #heyletsgo是不明确的名称,不会让调试应用程序变得更容易。

Use event.preventDefault() to prevent the form submission.使用event.preventDefault()来阻止表单提交。

On the backend, once again, remove any cruft and noise like the file read and import pdfkit, time .在后端,再次删除文件读取和import pdfkit, time等任何杂物和噪音。 It seems strange to add GET to the list of accepted verbs for the /path route (which is too generically-named, as is go ).GET添加到/path路由的接受动词列表中似乎很奇怪(这太笼统地命名了,就像go )。

Since you're using form data, request.get_data() can be request.form.get("data") where "data" is the key you want to retrieve from the parsed form.由于您使用的是表单数据,因此request.get_data()可以是request.form.get("data")其中"data"是您要从已解析的表单中检索的键。

Here's a minimal example to get you moving:这是一个让您动起来的最小示例:

templates/index.html : templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <h1>Welcome!</h1>
  <p>Type to search the database.</p>
  <form>
    <input id="search-term" type="text">
    <input type="submit" value="search">
  </form>
  <div id="result"></div>

<script>
$("form").submit(function (event) {
  event.preventDefault();
  var data = $("#search-term").val();
  $.ajax({
    type: "POST",
    url: "search",
    data: {data},
    success: data => $("#result").text(data),
    error: res => console.error(res),
  });
});      
</script>
</body>
</html>

app.py : app.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/search", methods=["POST"])
def search():
    data = request.form.get("data")
    print(data)
    return data

@app.route("/")
def index():
    return render_template("index.html")

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

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

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