2014-02-20 180 views
3

这是我的看法功能阿贾克斯后数据

@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') 

我得到“没有”

有人可以告诉我如何解决这一问题?

回答

8

您正在设置内容类型为application/json,但发送的数据是application/x-www-form-urlencoded

设置正确的内容类型:

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

或者更好的是,通过完全省略contentType键离开它的默认值。

+0

谢谢...它解决了问题 –