【发布时间】:2015-03-10 08:56:31
【问题描述】:
对于我在 Flask 中的网络应用程序,我需要在一次提交中发送两个发布请求:
第一个是发送我的表单数据,这里一切正常。
但是有一个字段不能通过表单(Tag-Field)发送。所以我想通过 javascript 获取该字段的标签,然后使用 $.ajax 发布请求将其发送到我的视图。 每次单击提交按钮时,我都会收到 $.ajax 发布请求的错误请求 (400) 错误。 另一个帖子请求工作正常。
这是我的 javascript:
script language="javascript">
function getTagList() {
var tagArray = new Array();
tagArray = $('#my-tag-list5').tags().getTags();
var tags = tagArray.toString();
console.log(tags);
request = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/dozent/fragenEingeben",
data: JSON.stringify(tags),
success: function (data) {
console.log(data.tags);
},
});
}
</script>
调用脚本和表单提交的按钮如下所示:
<li class="next"><button type="submit" class="btn btn-success next btnPager btnPagerRight" name="createAndActivate" value="createAndActivate" onclick="getTagList();">Speichern</br><i>~ und freigeben ~</i></button></li>
当我在 Flask 中打印 request.form 时,我在 Python 控制台中得到了这个:
ImmutableMultiDict([])
127.0.0.1 - - [12/Jan/2015 15:25:09] "POST /dozent/fragenEingeben HTTP/1.1" 400 -
ImmutableMultiDict([('createAndActivate', u'createAndActivate'), ('option2[]', u'answer1'), ('option2[]', u'answer2'), ('option2[]', u'answer3'), ('option2[]', u''), ('option[]', u'answer'), ('option[]', u''), ('question', u'Question'), ('time', u'10s')])
127.0.0.1 - - [12/Jan/2015 15:25:10] "POST /dozent/fragenEingeben HTTP/1.1" 302 -
这是我的浏览器中的错误:
POST http://127.0.0.1:5000/dozent/fragenEingeben 400 (BAD REQUEST) jquery.min.js:4
send jquery.min.js:4
m.extend.ajax jquery.min.js:4
getTagList fragenEingeben:240
onclick fragenEingeben:227
这是我的烧瓶视图:
#create question
@app.route('/dozent/fragenEingeben', methods=['GET','POST'])
@login_required
def fragenEingeben():
if request.method == 'POST':
print request.form
#If button "Speichern und freigeben" was clicked do the following
if request.form['createAndActivate'] == 'createAndActivate':
tags = request.json['tags']
#Get ID of signed in lecturer
lecturer = getLecturerID((session['email'],))
#Write all in db
createAndActivateQuestion(request.form['question'],"tag",lecturer,request.form['time'],request.form.getlist('option[]'),request.form.getlist('option2[]'))
flash('Frage erfolgreich erstellt und aktiviert.')
return jsonify(tags=tags)
#If button "Speichern und nicht freigeben" was clicked do the following
elif request.form['createQuestion'] == 'createQuestion':
#Get ID of signed in lecturer
lecturer = getLecturerID((session['email'],))
#Write all in db
createQuestion(request.form['question'],"tag",lecturer,request.form['time'],request.form.getlist('option[]'),request.form.getlist('option2[]'))
flash('Frage erfolgreich erstellt.')
return redirect(url_for('fragenEingeben'))
else:
return redirect(url_for('statistik'))
else:
pass
return render_template('dozent/fragenEingeben.html')
当我想在视图中获取数据时,出现以下错误:
TypeError: 'NoneType' object has no attribute '__getitem__'
谁能解释为什么我在第一次发布请求时收到了错误的请求?
【问题讨论】:
-
您需要为此向我们展示您的 Flask 视图。
标签: ajax forms post flask httprequest