这是我的视图功能
@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')
我得到’无’
有人能告诉我如何解决这个问题吗?
解决方法:
您正在将内容类型设置为application / json,而是发送application / x-www-form-urlencoded数据.
设置正确的内容类型:
$.ajax({
url: '/share',
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: $('#share-form').serialize(),
或者更好的是,通过省略contentType键将其保留为默认值.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。