【问题标题】:ajax post data in flask view烧瓶视图中的ajax发布数据
【发布时间】:2014-03-21 22:33:09
【问题描述】:

这是我的视图函数

@app.route('/share', methods=['GET', 'POST'])
def share():
    form = ShareForm(request.form)
    if request.method == 'POST':
        title = form.title.data
        body = form.body.data
        share_id = form.share_id.data
        print 'form data %s %s %s' % (title, body, share_id)
        if not share_id:
            share = Shares(title, body, 'PUBLISHED', current_user.id)
            db.session.add(share)
            db.session.commit()
            form.share_id.data = share.id
        return jsonify({'status': 204, 'body': {'status': True}})
    else:
        return render_template('share.html', form=form)

ajax post请求代码

<script>
    $(function(){
      $('#share').on('click', function(e){
        e.preventDefault(); // preventing default click action
        $.ajax({
          url: '/share',
          type: 'post',
          contentType: "application/json; charset=utf-8",
          data: $('#share-form').serialize(),
          success: function(){
            console.log('success');
            console.log( $('#share-form').serialize());
          }, error: function(xhr, textStatus, errorThrown) {
            alert(xhr.responseText);
            console.log( $('#share-form').serialize());
          }});
        })
        //return false;
      });
</script>

在视图中,当我尝试打印请求对象时,我得到以下数据

print request.data
'title=adsl%3Blsaj%3Blj%3Bl&body=j%3Bas%3Bl%3Bl+&share_id='

但如果我尝试这样做,

print request.form.get('title', 'None')

我得到“无”

谁能告诉我如何解决这个问题?

【问题讨论】:

    标签: python ajax python-2.7 flask


    【解决方案1】:

    您将内容类型设置为application/json,但改为发送application/x-www-form-urlencoded 数据。

    设置正确的内容类型:

    $.ajax({
      url: '/share',
      type: 'post',
      contentType: "application/x-www-form-urlencoded",
      data: $('#share-form').serialize(),
    

    或者更好的是,通过完全省略 contentType 键将其保留为默认值。

    【讨论】:

      猜你喜欢
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 2018-05-17
      • 2015-03-10
      • 2018-04-05
      • 1970-01-01
      相关资源
      最近更新 更多