【问题标题】:Python Flask and JQuery.post Are Not Working TogetherPython Flask 和 JQuery.post 不能一起工作
【发布时间】:2021-11-29 04:44:48
【问题描述】:

我正在创建一个非常简单的仪表板来自动执行一项任务。 在这里安全不是问题,因为我只是本地主机。

JQuery 代码

$.post("/approve", data={"title":title,"content":content}, success=function(){
      window.location.reload(true)
});

烧瓶代码

@app.post('/approve')
def approve_topic():
  args = request.args
  print(args)
  json.dump(args, open("topics/"+uuid4().hex+".json", "w"))
  return {"status":"clear"}

结果(JSON 文件)

{}

预期结果

{"title":"whatever the title is", "content":"whatever the content is"}

知道为什么会这样吗? 我第一次运行它时它工作得很好,但现在无论我重置什么或我做什么它都不会工作。

【问题讨论】:

  • 旁注:如果您要在之后立即重新加载页面,那么使用 AJAX 有什么意义? AJAX 的全部目的是避免重新加载所有内容。如果你想这样做,那么就从一个正常的回发开始,然后你就可以节省到服务器的额外行程。
  • 试试:args = request.get_json(force=True)
  • @ADyson 请求已经是 POST 请求,我重新加载它以再次发布请求。
  • The request is already a POST request, and I reload it to post request again... 这不是我的意思。当一个就足够时,你会做两个请求。
  • 我建议使用调试器来探索请求对象中的可用选项,例如 request.form,并检查哪些包含您的数据。如果这不起作用,请确保您使用正确的方式使用 jQuery stackoverflow.com/questions/5570747/jquery-posting-json 发布 JSON

标签: javascript python jquery json flask


【解决方案1】:

我刚刚测试了代码,它在request.form 上运行良好。 烧瓶代码:

from flask import Flask, request
app = Flask(__name__)

# you can ignore this function as you're doing request on same origin
@app.after_request
def allow_cors_origin(response):
    """Resolve CORS error"""
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,OPTIONS")
    return response


@app.route("/echo", methods=["POST"])
def echo():
    data = request.form
    print(data)  # Output: ImmutableMultiDict([('a', '1')])
    return data 


app.run(debug=True)

jQuery 代码:

$.post("http://localhost:5000/echo", {a: 1}, r=>console.log("response: ", r))
// Output: response:  {a: '1'}

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2018-03-11
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    相关资源
    最近更新 更多