【问题标题】:JSON "POST" to Flask View doesn't workJSON“POST”到烧瓶视图不起作用
【发布时间】:2012-12-19 05:26:35
【问题描述】:

我想通过 POST 将一些 JSON 发送到我的 Flask 视图。

这是我的代码

js:

$.post('/blog/add/ajax',
  { "title": "hallo", "article": "test" },
  function(data) {
    console.log(data.title);
    console.log(data.article);
  },
  "json"
);

py:

@app.route('/blog/add/ajax', methods=['POST', 'GET'])
def add_blog_ajax():
    if request.method == 'POST':
        title = request.json['title']
        article = request.json['article']
        blog = Blog(title, article)
        db.session.add(blog)
        db.session.commit()
        return jsonify(title=title, article=article)

错误:

TypeError: 'NoneType' object has no attribute '__getitem__'

我不知道该怎么做,这里出了什么问题。

【问题讨论】:

  • 基于错误,我建议 request.json 没有正确填写。你能输出request.body 和标题吗?也许您没有发送适当的内容类型。
  • request.body 有内容吗?
  • @sberry jup 有内容
  • 表示content-type没有触发json的更新。

标签: jquery python json post flask


【解决方案1】:

好的,我有一个解决方案:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "/blog/add/ajax",
  data: JSON.stringify({title: 'hallo', article: 'test'}),
  success: function (data) {
    console.log(data.title);
    console.log(data.article);
  },
  dataType: "json"
});

这对我有用!

【讨论】:

  • 请注意 contentType 已指定。
  • 一个简单的捷径是在你想作为data传递的对象上使用JSON.stringify。所以你的数据参数将等于JSON.stringify({title: 'hallo', article: 'test'})
猜你喜欢
  • 2016-12-23
  • 1970-01-01
  • 2014-04-11
  • 2018-06-19
  • 2020-07-24
  • 1970-01-01
  • 2016-09-02
  • 2017-12-20
  • 1970-01-01
相关资源
最近更新 更多